Java自定义异常且格式化
一、前言
要在Spring Boot中创建自定义异常并使用@RestControllerAdvice
处理它们,可以按照以下步骤:
-
定义自定义异常类:
public class CustomException extends RuntimeException { private String message; private int errorCode; public CustomException(String message, int errorCode) { super(message); this.message = message; this.errorCode = errorCode; } public String getMessage() { return message; } public int getErrorCode() { return errorCode; } }
-
创建
@RestControllerAdvice
类:import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(CustomException.class) public ResponseEntity<ErrorResponse> handleCustomException(CustomException ex) { ErrorResponse errorResponse = new ErrorResponse(ex.getMessage(), ex.getErrorCode()); return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); } } class ErrorResponse { private String message; private int errorCode; public ErrorResponse(String message, int errorCode) { this.message = message; this.errorCode = errorCode; } // Getters and setters }
-
在应用中抛出自定义异常:
@RestController public class SampleController { @GetMapping("/test") public String test() { throw new CustomException("Custom error message", 1234); } }
这样,自定义异常会被@RestControllerAdvice
处理,并返回格式化的错误响应。