Matej J
Matej J

Reputation: 643

Control exception output format

I am trying to control how the error is going to be displayed.

I am trying to do something similar to this: https://stackoverflow.com/a/22271986/10538678 but on global level (for every exception thrown). I tried this example described in this question, but i have no idea how to implement this globally

Instead of:

Exception in thread "threadName" Name of Exception : Description
... ...... ..  // Call Stack

For example i want error to display:

<Error>
    <ErrorCode>customErrorCode</ErrorCode>
    <ErorMsg>Description</ErorMsg>
    <ErrorClass>className</ErrorClass>
    <ErrorThread>threadName</ErrorThread>
</Error>

EDIT: I have multiple dependencies which use exception handling and i cannot modify them.

Upvotes: 0

Views: 144

Answers (2)

user11725421
user11725421

Reputation:

What you need is to add ControllerAdvice. In your case it would be something like this:

@ControllerAdvice
public class RestResponseEntityExceptionHandler 
  extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = { Exception.class})
    protected ResponseEntity<String> handleException(Exception e) {
        String bodyOfResponse = "This should be application specific";
        return new ResponseEntiy<String>(bodyOfResponse )
    }
}

Upvotes: 1

Starmixcraft
Starmixcraft

Reputation: 397

You can set a DefaultExceptionHandler with Thread.setDefaultUncaughtExceptionHandler(); as the name tells you, it handels uncaught Exception thrown with throw but not printed stack trace!

But if somewhere in youre code you used try{}catch(Exception e){e.printStackTrace();} you cant do enything to change the way it is presented

Upvotes: 0

Related Questions