-2

i have a rest api:

@RestController

.....

@PostMapping(value = "/v1/ms/prop")
    public @ResponseBody ResponseEntity<Object> orch(@RequestBody @Valid Request request){
        
            
        

Response response = serv.prop(request);
            return ResponseEntity.ok(response);

and serv.prop(request):

Response response = new Response ();
    
    try {
        calculate(**data**);
        callExternalService();
    } catch (Exception e) {

   **//intercept status error code**
   **// writeError(data,errorStatusCode)**
        
    } finally {
        writeAuditOperation(auditLog);
        MDC.clear();
    }

Inside the catch, i want, ONLY IN this api rest, intercept the type of error (400,404,500,502 ecc ecc ) and call an external service that log this error.

Thanks for the help

Alex
  • 111
  • 1
  • 13
  • You can able to get details of HTTP status code if your `calculate();` or `callExternalService();` throws error with HTTP status code. Share details about what exceptions being thrown from these methods. – Ashish Patil May 16 '22 at 14:29
  • i have update my post – Alex May 16 '22 at 14:57
  • I mean, do you know what type of exceptions being thrown from `calculate()` or `callExternalService()` – Ashish Patil May 16 '22 at 14:59
  • calculate -> 5XX, callExternalService() -> 4XX – Alex May 16 '22 at 15:14
  • https://stackoverflow.com/questions/37302615/extract-http-status-code-from-java-io-ioexception let us know if this helps, if not, will put some answer. – Ashish Patil May 16 '22 at 16:08

1 Answers1

1

Rather than manually handling Exceptions in your controller, you should try @ExceptionHandler.

Check: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

agulowaty
  • 191
  • 7
  • my controller has 3 postmapping methods. How can i do for apply at only one of these methods? And in case of error, i call, inside the service, an external service for comunicate the type of error and other data that are presents ONLY inside the service (not the controller) – Alex May 16 '22 at 14:36
  • Maybe you should re-consider your general application architecture. Instead of trying to intercept status codes from the call to external services, try to translate their responses to meaningful exceptions in you applications and pick them in you `catch` blocks (instead of general `Exception` type). – agulowaty May 16 '22 at 15:25