我为我的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“决定”要发送的状态代码?
答案 0 :(得分:1)
从Java和Spring角度来看,最好使用@ControllerAdvice和@ExceptionHandler。
根据错误代码的值,没有标准。但是您可以:
https://developer.paypal.com/docs/api/reference/api-responses/#http-status-codes
https://developer.paypal.com/docs/classic/api/errors/#10000-to-10099
答案 1 :(得分:0)
由于错误的类型可能因应用程序而异,并且不可能对所有这些错误都具有统一的HTTP状态,因此我通过创建将错误代码映射到HTTP状态的自定义映射器解决了该问题。
由于错误代码是唯一的,并且每个错误代码都用于特殊的异常处理,因此我可以将错误代码映射到Http状态。
答案 2 :(得分:0)
您始终可以在Exception中设置HttpStatus属性,并在Handler中仅获取状态值并在ResponseEntity中对其进行配置。基本上,HttpStatus取决于执行任务的上下文。您的技术或业务异常可以返回400、404、409等。我认为不错的解决方案是在引发适当的异常期间定义HttpStatus。 如果您不想为每个HttpStatus定义许多异常,则可以使用org.springframework.web.server.ResponseStatusException。