代码之家  ›  专栏  ›  技术社区  ›  Almas Abdrazak

UncaughtExceptionHandler中的转义实例

  •  0
  • Almas Abdrazak  · 技术社区  · 8 年前

     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) 在所有异常之间切换?

    1 回复  |  直到 8 年前
        1
  •  0
  •   Yogesh Badke    8 年前

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

    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());
     }