How to replace ErrorController deprecated function on Spring Boot?

Viewed 12078

Have a custom error controller on Spring boot:

package com.example.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.boot.web.servlet.error.ErrorController;
import javax.servlet.http.HttpServletRequest;


@Controller
public class CustomErrorController implements ErrorController
{
    @RequestMapping("/error")
    public String handleError(HttpServletRequest request)
    {
        ...
    }

    @Override
    public String getErrorPath()
    {
        return "/error";
    }
}

But, when compile says: getErrorPath() in ErrorController has been deprecated. Ok, i found information: use server.error.path property. Ok, add this in application.properties and delete the function, but now says: CustomErrorController is not abstract and does not override abstract method getErrorPath() in ErrorController, ¿need a deprecated function?.

How to made the custom error controller?, the ErrorController requires getErrorPath but it is deprecated, what is the correct alternative?.

4 Answers

Starting version 2.3.x, Spring boot has deprecated this method. Just return null as it is anyway going to be ignored. Do not use @Override annotation if you want to prevent future compilation error when the method is totally removed. You can also suppress the deprecation warning if you want, however, the warning (also the @Override annotation) is helpful to remind you to cleanup/fix your code when the method is removed.

@Controller
@RequestMapping("/error")
@SuppressWarnings("deprecation")
public class CustomErrorController implements ErrorController {

     public String error() {
        // handle error
        // ..
     }

     public String getErrorPath() {
         return null;
     }
}
@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public ModelAndView handleError(HttpServletResponse response) {
        int status = response.getStatus();
        if ( status == HttpStatus.NOT_FOUND.value()) {
            System.out.println("Error with code " + status + " Happened!");
            return new ModelAndView("error-404");
        } else if (status == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
            System.out.println("Error with code " + status + " Happened!");
            return new ModelAndView("error-500");
        }
        System.out.println(status);
        return new ModelAndView("error");
    }
}

there is an @ControllerAdvice annotation

@ControllerAdvice
public class MyErrorController {


   @ExceptionHandler(RuntimeException.class)
   public String|ResponseEntity|AnyOtherType handler(final RuntimeException e) {
     .. do handle ..
   }

   @ExceptionHandler({ Exception1.class, Exception2.class })
   public String multipleHandler(final Exception e) {

   }

}
  1. To handle errors, There is no need to define a controller class implementing an error controller.
  2. To handle errors in your entire application instead of writing

    @Controller
     public class CustomErrorController implements ErrorController{
      @RequestMapping("/error")
      public String handleError(HttpServletRequest request)
        {
        ...
        }
      }
    

use the below class

@ControllerAdvice
 public class myExceptionHandler extends ResponseEntityExceptionHandler {

  @ExceptionHandler(Exception.class)
  public final ResponseEntity<YourResponseClass> handleAllExceptions(Exception ex, WebRequest request) {
    YourResponseClassexceptionResponse = new YourResponseClass(new Date(), ex.getMessage());// Its an example you can define a class with your own structure
    return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
  }

  @ExceptionHandler(CustomException.class)
  public final ResponseEntity<YourResponseClass> handleAllExceptions(Exception ex, WebRequest request) {
    YourResponseClass exceptionResponse = new YourResponseClass(new Date(), ex.getMessage()); // For reference 
    return new ResponseEntity<YourResponseClass>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
  }

   @ExceptionHandler(BadCredentialsException.class)
  public final ResponseEntity<YourResponseClass> handleBadCredentialsException(BadCredentialsException ex, WebRequest request){
        YourResponseClass exceptionResponse = new YourResponseClass(new Date(), ex.getMessage());// For refernece 
            return new ResponseEntity<>(exceptionResponse, HttpStatus.UNAUTHORIZED);          
  }  

}

  1. The class above annoted with @ControllerAdvice acts as custom exception handler and it handles all the expecptions thrown by ur application. In above code sample only three exceptions are showed for understanding. It can handle many exceptions

  2. In your application if there's any exception thrown it will come to this class and send the response back. You can have a customized message and structure as per ur needs.

Related