【问题标题】:Why is ErrorController not throwing my custom exception class?为什么 ErrorController 不抛出我的自定义异常类?
【发布时间】:2020-02-20 04:05:44
【问题描述】:

我的一项服务引发了自定义异常 (SearchException)。异常定义为:

@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public class SearchException extends Exception {
    private static final long serialVersionUID = 1L;
}    

然后我有一个 ErrorController:

@Controller
public class TVFErrorController implements ErrorController  {


    private static final Logger log = LoggerFactory.getLogger(TVFErrorController.class);


    @RequestMapping("/error")
    public String handleError(HttpServletRequest request, Exception e) {
        //do something like logging
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        if (status!=null){
            log.error("An error occured: status: "+status.toString());
        }
        if (e != null){
            log.error("Exception that occured: "+e.toString());
            e.printStackTrace();
        }
        return "error";
    }

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

大部分都按预期工作,唯一的问题是描述控制器中异常的日志消息总是报告 java.lang.Exception 而不是我的 SearchException。

【问题讨论】:

  • 尝试做:if (e instanceof SearchException ) { log.error("Exception that occured: "+((SearchException) e).toString());}

标签: spring spring-boot spring-mvc


【解决方案1】:

大部分都按预期工作,唯一的问题是描述控制器中异常的日志消息总是报告 java.lang.Exception 而不是我的 SearchException。

我想这是因为您的错误处理程序在收到异常类型时将其从 SearchException 擦除到 Exception

public String handleError(HttpServletRequest request, Exception e)

我认为您需要为您的 SearchException 创建明确的错误处理程序

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 2021-05-07
    • 2010-12-09
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多