java - 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“决定”发送哪个状态码?
解决方案
从 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
推荐阅读
- java - 在循环中运行方法以从数组列表中获取 Max、Min
- google-apps-script - Google表格中的Google App Script - 在列中查找相同的值并将数据行作为变量获取
- php - PHP:在第 n 次出现后插入 HTML标签
- php - Laravel vue 在 api 路由中返回 401 错误
- r - r - 从分组值列表中删除异常值
- reactjs - 如何将 React HOC 与 Typescript 一起使用
- reactjs - Reactjs - 根据传递的属性选择具有不同第一个选项的框
- mysql - MYSQL - 无法与 Group By 2 Columns 正确连接
- javascript - 如何在下拉列表中动态显示多个复选框列表
- python - Anaconda 安装错误 winerror2 也提示 is not worming