您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。