如何在Spring Boot上替换已弃用的错误控制器函数?

0s0u357o  于 2022-10-04  发布在  Spring
关注(0)|答案(5)|浏览(197)

在Spring引导上有一个定制的错误控制器:

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";
    }
}

但是,当编译说:getErrorPath() in ErrorController has been deprecated。好的,我找到信息了:使用server.error.path属性。好的,在application.properties中添加这个并删除该函数,但现在说:CustomErrorController is not abstract and does not override abstract method getErrorPath() in ErrorController,需要一个过时的函数?

如何制作定制的差错控制器?,ErrorController需要getErrorPath却被弃用,正确的替代方案是什么?

6yt4nkrj

6yt4nkrj1#

从2.3.x版开始,Spring Boot已弃用此方法。只要返回NULL,因为它无论如何都会被忽略。如果希望在完全移除方法时防止将来出现编译错误,请不要使用@Overover注解。如果需要,您也可以抑制弃用警告,但是,警告(也是@Override注解)有助于在移除方法时提醒您清理/修复代码。

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

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

     public String getErrorPath() {
         return null;
     }
}
xriantvc

xriantvc2#

@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");
    }
}
1qczuiv0

1qczuiv03#

有一个@ControllerAdvice注解

@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) {

   }

}
7gyucuyw

7gyucuyw4#

1.要处理错误,不需要定义实现错误控制器的控制器类。
1.处理整个应用程序中的错误,而不是编写

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

使用下面的类

@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.上面用@ControllerAdacy标记的类充当自定义异常处理程序,它处理您的应用程序抛出的所有预期。在上面的代码示例中,为了便于理解,只显示了三个例外。它可以处理许多异常
1.在您的应用程序中,如果抛出任何异常,它将转到这个类并发送回响应。您可以根据自己的需要定制消息和结构。

u5i3ibmn

u5i3ibmn5#

@Controller
public class AppErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

        if(status != null) {
            int statusCode = Integer.valueOf(status.toString());

            if (statusCode == HttpStatus.FORBIDDEN.value()) {
                return "errorpages/error-403";
            } else if (statusCode == HttpStatus.NOT_FOUND.value()) {
                return "errorpages/error-404";
            } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                return "errorpages/error-500";
            }
        }
        return "error/error";
    }
}

相关问题