【问题标题】:Response object along with http status code响应对象以及 http 状态码
【发布时间】:2018-10-17 07:14:46
【问题描述】:

我想连同响应对象一起返回 http 状态码。如果我只是在失败场景中返回响应对象,则状态将返回为 200。但我想将服务返回的状态(例如:403)与响应对象一起发送。但是下面的代码只是返回消息以及状态。在这种情况下,我想要响应对象 orderdetails 对象,它具有失败原因和其他字段。任何帮助如何将对象传递回客户端?

@Component
public class OrderController {

@Autowired
private OrderService service;

    public OrderDetails createOrder(final OrderDetails orderVO) {
        try {
            OrderDetails orderVO = service.createOrder() // service call
        } catch(OrderException e) {
            OrderDetails orderVO = e.getOrderDetails(); // even in exception cases backend liberary sends same object with error messages        
            ServiceException exception = new ServiceException(e.getStatus(), e.getMessage());
            exception.setOrderDetails(orderVO);
            throw exception;
        }
        return orderVO; 
    }
}

【问题讨论】:

标签: java spring rest exception-handling


【解决方案1】:

你可以定义一个@ControllerAdvice 并在那里添加你的错误处理逻辑。

@ControllerAdvice
public class SampleControllerAdvice {

     @ExceptionHandler(ServiceException.class)
     public ResponseEntity<YourResponse> handleServiceException(ServiceException e) {
         // YourResponse could be any serializable type (including ServiceException)
         YourResponse body = ...
         // Set the desired HTTP response headers
         HttpHeaders responseHeaders = ...
         // Set the desired HTTP response status
         HttpStatus status = ...
         return new ResponseEntity<YourResponse>(body, headers, status);
     }

}

如果ServiceException 抛出异常,则调用处理程序方法。

【讨论】:

    【解决方案2】:

    可能 OrderException 中的 OrderDetails 为空... 因此,使用 exception.setOrderDetails(orderVO); 您将 null 放入 Exception 中!!!

    【讨论】:

      猜你喜欢
      • 2016-12-18
      • 2020-09-26
      • 2016-05-21
      • 1970-01-01
      • 2013-10-20
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 2012-06-12
      相关资源
      最近更新 更多