Home > database >  How to pass variable from @controller to @controlleradvice
How to pass variable from @controller to @controlleradvice

Time:10-11

right now I make custom handler using controlleradvice and is working well. I want to add additional info to the custom validation that "the invoice process has been failed". how do I achieve that ? thank you

CodePudding user response:

You can define you own exception object and uses it to pass the data from the controller method to the exception handler method.

First define an exception as :

public class InvoiceException extends RuntimeException {
   
    private Long invoiceId;
    private String additionalInfo;
}

Then in the controller if you check that if violates the related business rules, create an instance of this exception and throw it :

public class InvoiceController {

  
    @PostMapping("/invoice")
    public Long processInvoice(InvoiceRequest request){
       
          if(fail) {
             throw new InvoiceException(invoiceId, "foobar");
          }       ​
   ​}

}

In the @ContorllerAdvice , you can then access these data from the exception instance :

@ControllerAdvice
public class MyExceptionHandler {

 ​@ExceptionHandler(InvoiceException.class)public ResponseEntity<ErrorMessage> handle(InvoiceException ex) {
 ​
      
 ​}
}
  • Related