13 예외처리
@Slf4j
@Controller
@RequestMapping("/error")
public class ErrorController {
@GetMapping("/test")
public void getTestError(HttpServletResponse resp) throws IOException {
resp.sendError(400, "에러 발생");
}
@GetMapping("/404")
public String get400Error(){
return "error/404";
}
// 404 에러 처리 - JSON 응답
@GetMapping(value = "/404", produces = "application/json")
@ResponseBody
public ResponseEntity<Map<String, Object>> get404ErrorJson() {
Map<String, Object> errorDetails = new HashMap<>();
errorDetails.put("status", 404);
errorDetails.put("error", "Not Found");
errorDetails.put("message", "Page not found");
errorDetails.put("path", "/error/404");
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
@GetMapping("/500")
public String get500Error() {
return "error/500";
}
// 500 에러 처리 - JSON 응답
@GetMapping(value = "/500", produces = "application/json")
@ResponseBody
public ResponseEntity<Map<String, Object>> get500ErrorJson() {
Map<String, Object> errorDetails = new HashMap<>();
errorDetails.put("status", 500);
errorDetails.put("error", "Internal Server Error");
errorDetails.put("message", "An unexpected error occurred");
errorDetails.put("path", "/error/500");
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
@GetMapping("/runtime")
public void runtimeException() {
throw new RuntimeException("runtime exception 발생");
}
// Runtime Exception 처리 - JSON 응답
@GetMapping(value = "/runtime", produces = "application/json")
@ResponseBody
public ResponseEntity<Map<String, Object>> runtimeExceptionJson() {
Map<String, Object> errorDetails = new HashMap<>();
errorDetails.put("status", 500);
errorDetails.put("error", "Internal Server Error");
errorDetails.put("message", "Runtime exception 발생");
errorDetails.put("path", "/error/runtime");
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
@GetMapping(value = "/illegal")
@ResponseBody
public ResponseEntity<Map<String, Object>> IllegalExceptionHtml() {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "타입 에러", new IllegalArgumentException());
}
@GetMapping(value = "/illegal", produces = "application/json")
@ResponseBody
public ResponseEntity<Map<String, Object>> IllegalExceptionJson() {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "타입 에러", new IllegalArgumentException());
}
}
Last updated