Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace ErrorController deprecated function on Spring Boot?

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?.

like image 850
e-info128 Avatar asked Mar 02 '23 08:03

e-info128


2 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;
     }
}
like image 116
TuaimiAA Avatar answered Mar 04 '23 22:03

TuaimiAA


@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");
    }
}
like image 41
Lime莉茉 Avatar answered Mar 04 '23 20:03

Lime莉茉