Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stacktrace of exceptions in Spring Rest responses

I have few Rest web services implemented through Spring. The problem is that if any exception is thrown the webservice returns json object with formatted error message that contains stacktrace. Can I have a single point of handling exceptions, and return my custom json objects with messages that wouldn't contain stacktrace?

I see descriptions for spring mvc but im not really using that for building my views etc.

like image 396
Taks Avatar asked Aug 21 '14 19:08

Taks


2 Answers

I know it's too late, but just pointing out some solutions that may help others!

case 1: if you're using application.properties file, add following line to your properties file.

server.error.include-stacktrace=on_trace_param

case 2: if you're using application.yml file, add following line to your yml file.

server:
  error:
    include-stacktrace: on_trace_param

case 3: In case, none of them works, try following changes:

Try to suppress the stack trace by overriding fillInStackTrace method in your exception class as below.

public class DuplicateFoundException extends RuntimeException {
    @Override
    public synchronized Throwable fillInStackTrace() {
        return this;
    }
}

ps1: I referred this article.

like image 61
Demobilizer Avatar answered Sep 28 '22 09:09

Demobilizer


Spring provides an out of the box solution to handle all your custom exceptions from a single point. What you need is @ControllerAdvice annotation in your exception controller:

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler(Exception.class)
    public String exception(Exception e) {

        return "error";
    }
}

If you want to go deep into Springs @ExceptionHandler at individual controller level or @ControllerAdvice at global application level here is a good blog.

like image 25
Sandeep B Avatar answered Sep 28 '22 08:09

Sandeep B