在Spring Boot中,异常处理可以通过几种方式实现,以提高应用程序的健壮性和用户体验。这些方法包括使用@ControllerAdvice注解、@ExceptionHandler注解、实现ErrorController接口等。下面是一些实现Spring Boot异常处理的常用方法:
@ControllerAdvice和@ExceptionHandler@ControllerAdvice是一个用于全局异常处理的注解,它允许你在整个应用程序中处理异常,而不需要在每个@Controller中重复相同的异常处理代码。@ExceptionHandler用于定义具体的异常处理方法。
- @ControllerAdvice
- public class GlobalExceptionHandler {
-
- @ExceptionHandler(value = Exception.class)
- public ResponseEntity
- Map
body = new LinkedHashMap<>(); - body.put("timestamp", LocalDateTime.now());
- body.put("message", "An error occurred");
- return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
- }
-
- @ExceptionHandler(value = CustomException.class)
- public ResponseEntity
- Map
body = new LinkedHashMap<>(); - body.put("timestamp", LocalDateTime.now());
- body.put("message", ex.getMessage());
- return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
- }
- }
ErrorController接口如果你想自定义/error路径下的错误页面或响应,可以通过实现Spring Boot的ErrorController接口来实现。
- @Controller
- public class CustomErrorController implements ErrorController {
-
- @RequestMapping("/error")
- public String handleError(HttpServletRequest request) {
- // 可以获取错误状态码和做其他逻辑处理
- Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
- if (status != null) {
- int statusCode = Integer.parseInt(status.toString());
- // 根据状态码返回不同的视图名或模型
- }
- return "errorPage"; // 返回错误页面的视图名
- }
-
- @Override
- public String getErrorPath() {
- return "/error";
- }
- }
ResponseEntityExceptionHandler扩展通过扩展ResponseEntityExceptionHandler类,你可以覆盖其中的方法来自定义处理特定的异常。这个类提供了一系列方法来处理Spring MVC抛出的常见异常。
- @ControllerAdvice
- public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
-
- @Override
- protected ResponseEntity
- HttpHeaders headers, HttpStatus status, WebRequest request) {
- Map
body = new LinkedHashMap<>(); - body.put("timestamp", LocalDateTime.now());
- body.put("status", status.value());
- List
errors = ex.getBindingResult() - .getFieldErrors()
- .stream()
- .map(x -> x.getDefaultMessage())
- .collect(Collectors.toList());
- body.put("errors", errors);
- return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
- }
- // 其他异常处理...
- }
通过这些方法,Spring Boot允许开发者灵活地处理应用程序中的异常,无论是全局处理还是特定异常的定制化处理,都能以优雅和统一的方式进行。