Exception Handling

Default Error Handling

500 Internal Server Error

Modify the method retrieveUser to throw exception when user is not found.

    @GetMapping("/users/{id}")
    public User retrieveUser(@PathVariable int id) {
        User user = service.findOne(id);
        if (user==null) {
            throw new UserNotFoundException("id-" + id);
        }
        return user;
    }

Create a new exception class which extends RuntimeException

package me.chairat.spring.boot.workshop.user;

public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException(String message) {
        super(message);
    }

}

You will get 500 Internal Server Error

get_user_error_500_error.png

404 Not Found

Add annotation to the exception class

@ResponseStatus(HttpStatus.NOT_FOUND)

And you will get the specified response

get_user_error_404_not_found.png

Custom Error Handling

All Errors

Create a new ExceptionResponse bean

package me.chairat.spring.boot.workshop.exception;

import java.util.Date;

public class ExceptionResponse {

    private Date timestamp;
    private String message;
    private  String detail;

    public ExceptionResponse(Date timestamp, String message, String detail) {
        this.timestamp = timestamp;
        this.message = message;
        this.detail = detail;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public String getMessage() {
        return message;
    }

    public String getDetail() {
        return detail;
    }

}

Create a new exception handler class which extends ResponseEntityExceptionHandler

package me.chairat.spring.boot.workshop.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.Date;

@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
        ExceptionResponse exceptionResponse =
                new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
        return new ResponseEntity(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

Now, you should see your customized error for all errors (which overrides 404 too)

get_user_custom_error_500.png

Specific Errors

Add a new exception handler method

    @ExceptionHandler(UserNotFoundException.class)
    public final ResponseEntity<Object> handleUserNotFoundExceptions(UserNotFoundException ex, WebRequest request) {
        ExceptionResponse exceptionResponse =
                new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
        return new ResponseEntity(exceptionResponse, HttpStatus.NOT_FOUND);
    }

And you will get proper 404 with customized response

get_user_custom_error_404.png

You should use the consistent exception response within your organization

No Comments

Back to top