Spring Boot在处理异常方面提供了许多内置功能,使得开发者能够更轻松地处理异常。以下是一些处理异常的最佳实践:
@ControllerAdvice
public class GlobalExceptionHandler {
// ...
}
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = {NotFoundException.class})
public ResponseEntity<ErrorResponse> handleNotFoundException(NotFoundException ex) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_FOUND.value(), ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
}
}
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {
// ...
}
@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());
if (statusCode == HttpStatus.NOT_FOUND.value()) {
return "404";
} else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
return "500";
}
}
return "error";
}
@Override
public String getErrorPath() {
return "/error";
}
}
@PostMapping("/users")
public ResponseEntity<?> createUser(@Valid @RequestBody User user) {
// ...
}
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = {MethodArgumentNotValidException.class})
public ResponseEntity<ErrorResponse> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
}
@RestControllerAdvice
public class GlobalExceptionHandler {
// ...
}
遵循这些最佳实践,您将能够更轻松地处理Spring Boot应用程序中的异常,并为用户提供更好的错误体验。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。