Spring boot-自定义休息控制器异常处理HTTP状态

问题描述 投票:0回答:3

我为我的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-boot http-status-codes spring-restcontroller
3个回答
0
投票

由于错误的类型可能因应用程序而异,并且不可能对所有这些错误都具有通用的HTTP状态,所以我通过创建将错误代码映射到HTTP状态的自定义映射器解决了它。

由于错误代码是唯一的,并且每个错误代码都用于特殊的异常处理,所以我可以将错误代码映射到Http状态。


0
投票

您可以始终在Exception中设置HttpStatus属性,并在Handler中仅获取状态值并在ResponseEntity中对其进行配置。基本上,HttpStatus取决于执行任务的上下文。您的技术或业务异常可以返回400、404、409等。我认为不错的解决方案是在引发适当的异常期间定义HttpStatus。如果您不想为每个HttpStatus定义许多异常,则可以使用org.springframework.web.server.ResponseStatusException。


0
投票

answer可以为您提供帮助。在本文中,您将找到不同的情况以及相关的HTTP代码状态'

© www.soinside.com 2019 - 2024. All rights reserved.