0

I am trying to send stack trace in api response if Spring Boot is running in profiles other than production so that it will be easy to debug issues.

I already tried \r and \n but they are printed as is. What I want is new line should be displayed instead of \n.

I have tried both Apache Commons Library and my custom converter to get stack trace in String format.

//Using Apache Commons library 
private String getStackTrace(Throwable ex) {
        return ExceptionUtils.getStackTrace(ex);
}

//Custom
    private String getCustomStackTrace(Throwable throwable) {
        //add the class name and any message passed to constructor
        StringBuilder result = new StringBuilder();
        result.append(throwable.toString());
        String NL = System.getProperty("line.separator");

        //add each element of the stack trace
        for (StackTraceElement element : throwable.getStackTrace()){
          result.append(element);
          result.append(NL);
        }
        return result.toString();
      }

output Json I am getting in Postman :

{
    "apiStackTrace": "java.lang.NullPointerException at xxx.xxx.Controller.getxxxxx(ABC.java:56)\n\t at xxx.xxx.xxxController$$FastClassBySpringCGLIB$$fd2ed167.invoke(<generated>)\n\tat org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)"
    "status": "failure",

}

Expected Json

{
"apiStackTrace": "
java.lang.NullPointerException at xxx.xxx.Controller.getxxxxx(ABC.java:56) 
 xxx.xxx.xxxController$$FastClassBySpringCGLIB$$fd2ed167.invoke(<generated> 
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)"

"status": "failure",

}

If you see what I am getting in apiStackTrace is having \n\t characters printed in response which is making it unreadable.

What I want is apiStackTrace should have explicit new lines to make it more readable.

So question is how to achieve this.

PS: This change is for DEV and QA profile only, so in postman response we want to see stacktrace so that we can avoid opening log file again and again.

GAURAV PANT
  • 135
  • 4
  • 11

0 Answers0