Exception Handling in springboot using @ExceptionHandler in the same class where the exception is thrown

26 Views Asked by At

The task I'm assigned is whenever a custom exception is thrown, I have to handle it such that it doesn't appear in the logs, and I'm expected to send a Json response to the Ui with status code. I was wondering can the method with @ExceptionHandler annotation be present in the same class. I don't want to create a global exception handler class. Is possible to do it this way? Or should I just use the usual try catch block in class A.

class A
{
  @GET
  @Path("/{instance_id}/default_runtime")
  @Produces(MediaType.APPLICATION_JSON)
  public Response f1()
  {
  //This function calls f2() function where the custom exception is thrown.
  }
}

class B
{
  public void f2()
  {
    //This function throws custom exception
  }

  @ExceptionHandler(CustomException.class)
  public ResponseEntity\<Object\> handleException(Exception e)
  {
    //returns a ResponseEntity
  }
}

0

There are 0 best solutions below