首页 > 解决方案 > Spring boot - 自定义rest控制器异常处理HTTP状态

问题描述

我为我的 Spring Boot 应用程序创建了一个自定义 REST 控制器异常处理程序......

@ControllerAdvice(annotations = RestController.class)
public class RestControllerExceptionHandler {    
  @ExceptionHandler(TechnicalException.class)
  public ResponseEntity handleTechnicalException(TechnicalException e) {    
    return new ResponseEntity<>(
        new RestErrorMessageModel(e.getErrorCode(), e.getMessage()), BAD_REQUEST
    );
  }

  @ExceptionHandler(BusinessException.class)
  public ResponseEntity handleBusinessException(BusinessException e) {    
    return new ResponseEntity<>(
        new RestErrorMessageModel(e.getErrorCode(), e.getMessage()), BAD_REQUEST
    );
  }

  @ExceptionHandler(ValidationException.class)
  public ResponseEntity handleValidationException(ValidationException e) {    
    return new ResponseEntity<>(
        new RestErrorMessageModel(e.getErrorCode(), e.getDetails()), BAD_REQUEST
    );
  }
}

...我处理验证、业务(由于违反业务规则而导致的异常)和技术(数据库相关、无效请求参数等)异常。

异常类有两个参数:errorCode(唯一枚举)和 message(异常详细信息)。

从示例中可以看出,对于所有情况,我都会返回 BAD_REQUEST (400) 状态,这不是最佳做法。

我想知道基于异常类别处理 HTTP 状态的最佳方法,例如:对于返回 BAD_REQUEST (400) 状态的验证错误是“好的”。

...或者有什么方法可以让spring-boot“决定”发送哪个状态码?

标签: javaspring-boothttp-status-codesspring-restcontroller

解决方案


从 java 和 spring 方面,使用 @ControllerAdvice 和 @ExceptionHandler 是最佳实践。

从错误代码的值来看,没有标准。但你可以:

1.遵循旧的https代码状态标准

  • 1xx 信息响应——请求已收到,继续处理
  • 2xx 成功——请求被成功接收、理解和接受
  • 3xx 重定向 - 需要采取进一步的措施才能完成请求
  • 4xx 客户端错误 – 请求包含错误语法或无法完成
  • 5xx 服务器错误 – 服务器未能满足明显有效的请求

2. 世界级公司的副本

https://developer.paypal.com/docs/api/reference/api-responses/#http-status-codes

3. 实现你自己的代码而不冲突 http 旧标准

https://developer.paypal.com/docs/classic/api/errors/#10000-to-10099


推荐阅读