在Spring Boot中如何实现异常处理?
在Spring Boot中,异常处理可以通过几种方式实现,以提高应用程序的健壮性和用户体验。这些方法包括使用@ControllerAdvice
注解、@ExceptionHandler
注解、实现ErrorController
接口等。下面是一些实现Spring Boot异常处理的常用方法:
1. 使用@ControllerAdvice
和@ExceptionHandler
@ControllerAdvice
是一个用于全局异常处理的注解,它允许你在整个应用程序中处理异常,而不需要在每个@Controller
中重复相同的异常处理代码。@ExceptionHandler
用于定义具体的异常处理方法。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public ResponseEntity<Object> handleGeneralException(Exception ex, WebRequest request) {
Map<String, Object> 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<Object> handleCustomException(CustomException ex, WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("message", ex.getMessage());
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
}
2. 实现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";
}
}
3. ResponseEntityExceptionHandler
扩展
通过扩展ResponseEntityExceptionHandler
类,你可以覆盖其中的方法来自定义处理特定的异常。这个类提供了一系列方法来处理Spring MVC抛出的常见异常。
@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("status", status.value());
List<String> 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允许开发者灵活地处理应用程序中的异常,无论是全局处理还是特定异常的定制化处理,都能以优雅和统一的方式进行。