Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-Boot - Error Handling

I'm trying to write error handler in Spring-Boot for my controllers that would catch most possible errors (Spring, sql etc.). So far I'm able to get JSON response with Nulls however i'm unable to put any data inside. When I try to get error message in I just receive a blank page.

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;

@RestController
public class BasicErrorController implements ErrorController {
    private static final String ERROR_PATH = "/error";

    @RequestMapping(value=ERROR_PATH)
    @ExceptionHandler(value = {NoSuchRequestHandlingMethodException.class, SQLException.class, IOException.class, RuntimeException.class, Exception.class})
    public ErrorBody defaultErrorHandler(HttpServletRequest request, Exception e) {     
        ErrorBody eBody = new ErrorBody();         
        eBody.setMessage(e.getCause().getMessage());
        return eBody;
    }
}
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class ErrorBody {
    private String dateTime;
    private String exception;
    private String url;
    private String message;
}
like image 282
Groth Avatar asked Feb 13 '15 13:02

Groth


People also ask

How do you handle errors in Spring boot?

You can define the @ExceptionHandler method to handle the exceptions as shown. This method should be used for writing the Controller Advice class file. Now, use the code given below to throw the exception from the API. The complete code to handle the exception is given below.

Does Spring provide exception handling?

Spring MVC provides exception handling for your web application to make sure you are sending your own exception page instead of the server-generated exception to the user. The @ExceptionHandler annotation is used to detect certain runtime exceptions and send responses according to the exception.

How does Spring boot handle exceptions in Java?

The exception handler method takes in an exception or a list of exceptions as an argument that we want to handle in the defined method. We annotate the method with @ExceptionHandler and @ResponseStatus to define the exception we want to handle and the status code we want to return.


2 Answers

Yo can do something like this:

 @ControllerAdvice
   public class ControllerExceptionTranslator {


    @ExceptionHandler(EntityNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    SimpleErrorMessage handleException(EntityNotFoundException exception){
        log.debug("Entity Not Found Exception {}",exception.getMessage());
        log.trace(exception.getMessage(),exception);
        return new SimpleErrorMessage("Entity not found","This resource was not found");
    }


    @ExceptionHandler({UsernameNotFoundException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    SimpleErrorMessage handleException(UsernameNotFoundException exception){
        log.debug("Username not found {}",exception.getLocalizedMessage());
        log.trace(exception.getMessage(),exception);
        return new SimpleErrorMessage("Unaouthorized"," ");
    }


}
like image 142
carlos_technogi Avatar answered Oct 05 '22 22:10

carlos_technogi


I was able to get to data about errors and send them as json properly by using "HttpServletRequest request" and reading information from request.

@RequestMapping(value = ERROR_PATH)
    public ErrorBody defaultErrorHandler(HttpServletRequest request) {....}
like image 36
Groth Avatar answered Oct 05 '22 21:10

Groth