响应对象以及 http 状态代码

Response object along with http status code

我想要 return http 状态代码以及响应对象。如果我只是 return 失败场景中的响应对象,状态将 returned 为 200。但是我想发送由服务 returned 的状态(例如:403)与响应对象。但是下面的一段代码只是 returning 消息和状态。在这种情况下,我想要响应对象 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; 
    }
}

您可以定义一个 @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 抛出异常,则调用处理程序方法。

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