
error.html λμ , JSON/λ¬Έμ μλ΅ + HTTP Statusλ‘ μ²λ¦¬ResponseEntity, @ExceptionHandler, @ControllerAdvice, HTTP status μ€κ³| κ°λ | μ€λͺ |
|---|---|
try { } catch | λΈλ‘ λ΄λΆμμ μμΈκ° λλ©΄ catchλ‘ λΆκΈ°νμ¬ λ³΅κ΅¬/μλ΅ μ²λ¦¬ |
throws Exception | λ©μλκ° μμΈλ₯Ό λμ§ μ μμμ μ μΈ(λ‘컬 μ²λ¦¬ μμ λ κ²½κ³ μ©) |
ResponseEntity<T> | μνμ½λ + ν€λ + λ°λλ₯Ό ν¨κ» μ μ΄νλ μλ΅ μ»¨ν μ΄λ |
@ExceptionHandler | ν΄λΉ 컨νΈλ‘€λ¬ ν΄λμ€ λ²μμμ λ°μν μμΈλ₯Ό ν κ³³μμ μ²λ¦¬ |
@ControllerAdvice | μ μ(λͺ¨λ 컨νΈλ‘€λ¬) μμΈ μ²λ¦¬. μ€μ½νλ₯Ό ν¨ν€μ§/μ΄λ Έν μ΄μ κΈ°μ€μΌλ‘ μ ν κ°λ₯ |
| HTTP Status | 2xx μ±κ³΅, 4xx ν΄λΌμ΄μΈνΈ μ€λ₯, 5xx μλ² μ€λ₯ λ± μλ΅ μλ―Έ μ²΄κ³ |
νμ리ν μ¬μ© μ μλ² μλ¬ β
templates/error.htmlλ‘ μλ μ΄λ(λ·° μλ΅).
REST APIλ λ·°λ₯Ό μ΄μ§ μμΌλ―λ‘ μνμ½λ/λ¬Έμ(JSON)λ‘ μλ΅ν΄μΌ ν¨.
try / catch@GetMapping("/detail/{id}")
@ResponseBody
public String detail() {
try {
// μλ¬ κ°λ₯ μ½λ
throw new Exception("μ΄λ°μ λ°μλ¬");
} catch (Exception e) {
System.out.println(e.getMessage()); // μλ² λ‘κ·Έ
return "μλ¬λ¨ γ
γ±"; // λ¨μ λ¬Έμμ΄ μλ΅
}
}
ResponseEntity@GetMapping("/detail/{id}")
public ResponseEntity<String> detail() {
try {
// ...
throw new Exception("μ΄λ°μ λ°μλ¬");
} catch (Exception e) {
return ResponseEntity
.status(400) // HttpStatus.BAD_REQUEST λ κ°λ₯
.body("μλͺ»λ μμ²: " + e.getMessage());
}
}
ResponseEntity.ok(body)μ²λΌ ν΅μΌν΄λλ©΄ μ’μμμ£Ό μ°λ μνμ½λ: 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 500 Internal Server Error
@ExceptionHandler@Controller
public class ItemController {
@GetMapping("/items/{id}")
public ResponseEntity<String> get(@PathVariable Long id) {
if (id < 0) throw new IllegalArgumentException("μμ ID λΆκ°");
return ResponseEntity.ok("OK");
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handle(Exception e) {
return ResponseEntity.status(400).body("컨νΈλ‘€λ¬ κ³΅ν΅ μλ¬: " + e.getMessage());
}
}
@ControllerAdvice@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleBadRequest(IllegalArgumentException e) {
return ResponseEntity.status(400).body("μλͺ»λ μμ²: " + e.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGeneral(Exception e) {
return ResponseEntity.status(500).body("μλ² μ€λ₯: μ μ ν λ€μ μλν΄μ£ΌμΈμ");
}
}
@ExceptionHandler > μ μ @ControllerAdviceμ€λ¬΄ ν
- κ³΅ν΅ μλ¬ μλ΅ DTO(μ:
{code, message, path, timestamp})λ₯Ό λ§λ€μ΄ νμ ν΅μΌ- λ‘κΉ μ
Slf4j/LogbackμΌλ‘ λ¨κΈ°κ³ , λ―Όκ°μ 보 μλ΅ κΈμ§
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
@ControllerAdvice
public class SpecificHandler {
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<String> mismatch(MethodArgumentTypeMismatchException e) {
return ResponseEntity.status(400).body("νλΌλ―Έν° νμ
μ€λ₯");
}
}
/detail/abc β Long λ³ν μ€ν¨ μ λ§€νλλ μμΈerror.htmlμ λ·° μλ΅μΌ λΏ, RESTμλ λ§μ§ μλλ€.