面试题答案
一键面试- 自定义异常类:
- 首先定义自定义异常类,继承自
RuntimeException
(也可以继承其他合适的异常类)。例如:
public class BusinessLogicException extends RuntimeException { public BusinessLogicException(String message) { super(message); } }
- 首先定义自定义异常类,继承自
- 使用
@ControllerAdvice
进行统一异常处理:- 创建一个异常处理类,使用
@ControllerAdvice
注解。在这个类中定义不同的异常处理方法,针对不同类型的异常返回合适的HTTP状态码和错误信息。
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<String> handleValidationExceptions( MethodArgumentNotValidException ex) { FieldError fieldError = ex.getBindingResult().getFieldError(); String errorMessage = fieldError.getDefaultMessage(); return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST); } @ExceptionHandler(BusinessLogicException.class) public ResponseEntity<String> handleBusinessLogicException( BusinessLogicException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.CONFLICT); } @ExceptionHandler(Exception.class) public ResponseEntity<String> handleAllExceptions( Exception ex) { return new ResponseEntity<>("System error occurred", HttpStatus.INTERNAL_SERVER_ERROR); } }
- 在上述代码中:
@ExceptionHandler(MethodArgumentNotValidException.class)
处理数据验证失败的异常,从异常中获取具体的字段错误信息,并返回HTTP 400状态码。@ExceptionHandler(BusinessLogicException.class)
处理业务逻辑异常,返回HTTP 409状态码(这里以409为例,可根据实际业务调整)。@ExceptionHandler(Exception.class)
处理其他未处理的系统错误,返回HTTP 500状态码。
- 创建一个异常处理类,使用
在实际的RESTful API接口中,如果发生数据验证失败、业务逻辑异常或系统错误,GlobalExceptionHandler
中的对应方法会被调用,返回给客户端合适的HTTP状态码和清晰的错误信息。