try{
throw new Exception("에러 보고싶어서 낸고얌");
} catch (Exception e) {
System.out.println(e.getMessage());
return "에러낫슴요";
}

throw Exception 추가 : 에러를 뱉을 수 있다는 경고문 같은 역할
String detail() throws Exception {
...
}
에러코드와 에러메세지를 보낼 수 있음
return 타입을 ResponseEntity<String> 으로~
@GetMapping("/detail/{id}")
ResponseEntity<String> detail(@PathVariable Long id, Model model) {
try{
throw new Exception("에러 보고싶어서 낸고얌");
} catch (Exception e) {
return ResponseEntity.status(에러코드).body("에러메세지");
}
}
에러코드
- 유저 잘못 : 4XX
- 서버 잘못 : 5XX
- 정상 : 200
: 알맞은 에러코드로 바꿔줌
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("에러메세지");
같은 클래스에서 발생하는 모든 에러 캐치
모든 에러를 캐치해주는 스프링 문법
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handler() {
return ResponseEntity.status(400).body("에러!!!!!");
}
모든 Controller 파일의 에러를 캐치함
// MyExceptionHandler.java
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handler() {
return ResponseEntity.status(400).body("에러!!!!!");
}
}
적절하게 @ExceptionHandler(예외) 넣어주면 됨
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<String> handler1() {
return ResponseEntity.status(400).body("타입 틀린!!!! 에러!!!!!");
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handler2() {
return ResponseEntity.status(400).body("에러!!!!!");
}
}