1

===============controller class==================

@PostMapping(path = "/products")
public ResponseEntity<ProductResponseDTO> saveProduct(@RequestBody Product product, @RequestHeader(name = "uuid", required = false) String uuid, HttpServletRequest request) throws Exception {
    request.setattribute("product",product);
    productRepo.save(product);
    ......
    .....
}

=======================Exception handler class==========================

@ControllerAdvice
public class GlobalErrorHandler{
    @ExceptionHandler({RuntimeException.class})
    public ResponseEntity<ErrorDetails> generateRuntimeException(RuntimeException re, WebRequest request, HttpServletRequest servletRequest) throws IOException {
        ErrorDetails errorDetails = new ErrorDetails();

            Product product=(Product)servletRequest.getAttribute("product");
            errorDetails.setTimestamp(LocalDateTime.now());
            errorDetails.setMessage("500");
            errorDetails.setDetails(re.getMessage());
            log.error("Exception occured3: " + re);
        }
        return new ResponseEntity<ErrorDetails>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
    }
]

I can see while executing the request.getAttribute("product"), it is showing null value. Once the exception happens, it is not getting inside the controller body, directly passing the control to exception class. As a result, resuest.setAttribute("product") is not setting the value to the request.

I Googled and tried several ways but still getting null values. Anyone please help me to get it resolved.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

0 Answers0