【问题标题】:Escape instance of in UncaughtExceptionHandlerUncaughtExceptionHandler 中的转义实例
【发布时间】:2017-07-21 05:32:46
【问题描述】:

我的休息控制器中有以下方法

 public DeferredResult<String> getWashHistory(@RequestParam(value = "sid", required = true, defaultValue = "") String sid,
            HttpServletResponse response, HttpServletRequest request,
            @RequestParam(value = "sort", defaultValue = "") String sortType,
            @RequestParam(value = "order", defaultValue = "") String order,
            @RequestParam(value = "limit", defaultValue = "") String limit,
            @RequestParam(value = "offset", defaultValue = "") String offset) {

        System.out.println("Thread: " + Thread.currentThread());
        final Integer managerId = checkSession(sid);
        DeferredResult<String> defResult = new DeferredResult<>();
        new Thread(() -> {
            System.out.println("tert: " + Thread.currentThread());
            Thread.currentThread().setUncaughtExceptionHandler(new SeparateThreadsExceptionHandler(defResult));
            final String result = washController.getWashHistory(managerId, order, sortType, limit, offset);
            defResult.setResult(result);
        }).start();
        return defResult;
    }

在 getWashHistory 中,我抛出了名为 InvalidUserInputException 的自定义异常,为了处理这个异常,我有以下类

public class SeparateThreadsExceptionHandler implements Thread.UncaughtExceptionHandler{
    private DeferredResult<String> dr;
    public SeparateThreadsExceptionHandler(DeferredResult<String> dr){
        this.dr = dr;
    }
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if(e instanceof InvalidUserInputException){
           InvalidUserInputException throwableException =  (InvalidUserInputException)e;
            dr.setResult(throwableException.error().getErrorCode());
        } else {
            throw new UnknownException("Unknown exception", "unKnown", "unKnown", null);
        }

问题是,在项目中我有很多自定义异常,是否可以避免使用public void uncaughtException(Thread t, Throwable e) 中的实例在所有异常之间切换?

【问题讨论】:

    标签: java spring-boot exception-handling


    【解决方案1】:

    您可以使用继承,如下所示

    class ParentException extends Exception {
          // based on .error() call showin in example, I am assuming you have some 
          // class that holds error code.
          private Error error;
    }
    

    那么子异常将是

    class InvalidUserInputException extends ParentException {
    // create constructor here that builds Error.
    }
    

    最后,

    if(e instanceof ParentException) {
        ParentException throwableException =  (ParentException)e;
                dr.setResult(throwableException.error().getErrorCode());
     }
    

    【讨论】:

    • 谢谢,正是我要找的东西
    猜你喜欢
    • 1970-01-01
    • 2015-03-13
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多