Ali
Ali

Reputation: 450

Spring boot change override exception responses

I am trying to customize exception responses and use my own response structure, I am using below way :

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler
{
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseEntity<String> handle(Exception ex, HttpServletRequest request)
    {
...
    }
}

But I have not accessed to the status code, I need status code that defined in exceptions via ResponseStatus:

@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
public class ExtendSubscriptionReminderNotExistException extends RuntimeException
{
}

Upvotes: 0

Views: 1615

Answers (3)

Qiu Zhou
Qiu Zhou

Reputation: 1275

With java reflection mechanism, you can do it like so:

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseEntity<String> handle(Exception ex, HttpServletRequest request) {
        if (ex instanceOf ExtendSubscriptionReminderNotExistException) {
            ResponseStatus status = ExtendSubscriptionReminderNotExistException.class.getAnnotation(ResponseStatus.class);
            return ResponseEntity.status(status.value()).body(ex.getMessage());
        }else{
            //if it's not ExtendSubscriptionReminderNotExistException, do sth different
        }
    }

Here is an useful article on how to read annotation in java: Java Reflection - Annotations

If you want to override ResponseStatusExceptionResolver, then you should extends AbstractHandlerExceptionResolver and implement your own doResolveException like ResponseStatusExceptionResolver did, then create a configuration extending WebMvcConfigurationSupport and override configureHandlerExceptionResolvers, then spring will pick up your own exception resolver over the default one. The logic behind this is here.

Upvotes: 1

Matt Pilaudeau
Matt Pilaudeau

Reputation: 107

I may be wrong on this one, but to me it doesn't really make sense to use @ResponseStatus annotation and a custom ErrorHandler at the same time. Annotations are supposed to make your code easier to understand and to avoid using such handlers.

If you really want to use the handler, I'd suggest to drop the annotation and store the corresponding status code in each exception (as a final static attribute for example).

Upvotes: 0

vishalsha95570
vishalsha95570

Reputation: 51

we cannot change exception messages. However determine we can change the code and class, and throw a new one by overriding the same class with the same code and different message.

Upvotes: 0

Related Questions