在Spring Boot中,Java异常处理可以通过以下几种方式实现:
@ControllerAdvice
注解:@ControllerAdvice
注解允许你在一个全局的类中处理所有控制器抛出的异常。你可以在这个类中定义一个或多个带有@ExceptionHandler
注解的方法,用于处理特定类型的异常。例如:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = {NotFoundException.class})
public ResponseEntity<String> handleNotFoundException(NotFoundException ex) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_FOUND.value(), ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(value = {IllegalArgumentException.class})
public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException ex) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
}
@ExceptionHandler
注解:你可以在控制器类中使用@ExceptionHandler
注解来处理特定类型的异常。例如:
@RestController
public class UserController {
@PostMapping("/users")
public User createUser(@RequestBody User user) {
// ...
}
@ExceptionHandler(value = {UserNotFoundException.class})
public ResponseEntity<String> handleUserNotFoundException(UserNotFoundException ex) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_FOUND.value(), ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
}
}
@ResponseStatus
注解:你可以在自定义异常类上使用@ResponseStatus
注解来设置HTTP状态码。例如:
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "User not found")
public class UserNotFoundException extends RuntimeException {
// ...
}
ErrorController
接口:实现ErrorController
接口允许你自定义错误页面和响应。例如:
@Controller
public class CustomErrorController implements ErrorController {
private static final String ERROR_PATH = "/error";
@RequestMapping(value = ERROR_PATH)
public ResponseEntity<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 ResponseEntity.status(HttpStatus.NOT_FOUND).body("Not Found");
} else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error");
}
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An unexpected error occurred");
}
@Override
public String getErrorPath() {
return ERROR_PATH;
}
}
这些方法可以根据项目的需求进行组合使用,以实现灵活且高效的异常处理。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。