· 1 min read

Writing cleaner logs by Disabling Stack Trace for Expected Response Exceptions

Placeholder

In spring boot, you can add @ResponseStatus annotation to an exception. By adding it, whenever the exception is thrown, the response will be according to the annotation properties.

For example: Whevener UserNotFoundException is thrown, the return value is 404 not found.

@ResponseStatus(HttpStatus.NOT_FOUND, reason="user could not be found")
class UserNotFoundException extends RuntimeException{
    UserNotFoundException(String message){
        super(message);
    }
}

We often create many such exception classes to make code cleaner. Throwing an exception is cleaner than multiple try-catch blocks.

The problem here is logs. Whenever exception is thrown, the log contains entire stack trace.

But these kind of exceptions are expected exceptions, in some sense they aren’t exceptions at all.

So, we can instead disable stack trace by adding the following to our exception class Source: StackOverflow.

    @Override
    public Throwable fillInStackTrace() {
        return this;
    }     

To make things better, we can create a custom exception class as follows

abstract class ExpectedResponseException extends RuntimeException{
    @Override
    public Throwable fillInStackTrace() {
        return this;
    }   
}
Back to Blog