SpringUser
SpringUser

Reputation: 1439

How to separate type of exception from it's message

In spring boot application I am handling exception using @ControllerAdvice. I am able to handle exception. my JSON message is status, error, exception and path. when I am printing exception string I am getting exception and and it's message also.

My quation is In exception parameter how to print only type of exception without it's message. because message I am printing in error?

One more Quation is that I am handling all types of exception using only one class i.e. Exception class. For every exception here I am getting status code as 500. Can we set different status code for different type of exception?

Can we pass status code here throw new NullPointerException("Null values are not allowed");

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ExceptionMessage> handleAllExceptionMethod(Exception ex,WebRequest requset,HttpServletResponse res) {   

        ExceptionMessage exceptionMessageObj = new ExceptionMessage();

        exceptionMessageObj.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        exceptionMessageObj.setError(ex.getLocalizedMessage());     
        exceptionMessageObj.setException(ex.toString());
        exceptionMessageObj.setPath(((ServletWebRequest) requset).getRequest().getServletPath());

        return new ResponseEntity<ExceptionMessage>(exceptionMessageObj, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);

}

enter image description here

Upvotes: 0

Views: 68

Answers (1)

rodridevops
rodridevops

Reputation: 1987

You need to set the name on your message like this:

exceptionMessageObj.setException(ex.getClass().getCanonicalName());

For example:

System.out.println(new NoClassDefFoundError().getClass().getCanonicalName());

Will return

java.lang.NoClassDefFoundError

Upvotes: 1

Related Questions