简体   繁体   中英

Response object along with http status code

I want to return http status code along with response object. If i just return response object in failure scenario the status is getting returned as 200. But i want to send the status that is returned by the service (eg: 403) along with the response object. But below piece of code is just returning message along with the status. I want response object in this case orderdetails object which has failure reasons and other fields. any help how to pass object back to client?

@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; 
    }
}

You could define a @ControllerAdvice and add your error handling logic there.

@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);
     }

}

If ServiceException gets throws the handler method is invoked.

Probably the OrderDetails in the OrderException is null... So with exception.setOrderDetails(orderVO); you put null in the Exception!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM