关于java:四SpringMVC异常处理

3次阅读

共计 4552 个字符,预计需要花费 12 分钟才能阅读完成。

1. SpringMVC 默认三个异样解决类

  • ExceptionHandlerExceptionResolver:解决 @ExceptionHandler 注解
  • ResponseStatusExceptionResolver:解决 @ResponseStatus 注解
  • DefaultHandlerExceptionResolver:解决 SpringMVC 自带的异样

如果以上 3 个异样解析器都无奈解决,会上抛给 tomcat,解决异样外部的默认工作流程:所有异样解析器顺次尝试解析,解析实现进行后续操作,解析失败,下一个解析器持续尝试解析。

2. @ExceptionHandler 注解异样

@ExceptionHandler 标注在办法上

  • 办法上写一个 Exception 用来接管产生的异样。
  • 要携带异样信息不能给参数地位写 Model,正确的做法是返回 ModelAndView。
  • 如果有多个 @ExceptionHandler 都能解决这个异样,准确优先。
@ExceptionHandler(value = { ArithmeticException.class, NullPointerException.class}) 
// 通知 SpringMVC, 这个办法专门解决这个类发送的所有异样
public ModelAndView handleException01(Exception exception) {System.out.println("handleException01..." + exception);
    ModelAndView view = new ModelAndView("myerror");
    view.addObject("ex", exception);    
    return view;
}

@ExceptionHandler 对立异样解决

  • 将 @ExceptionHandler 放在一个独自的类中,进行全局异样解决
  • 对立异样治理类须要通过 @ControllerAdvice 注解退出 IoC 容器中
  • 全局异样解决与本类异样解决同时存在,本类优先
@ControllerAdvice
public class MyException {
    // 解决空指针异样
    @ExceptionHandler(value = { NullPointerException.class})
    public ModelAndView handleException01(Exception exception) {System.out.println("全局的 handleException01..." + exception);
        ModelAndView view = new ModelAndView("myerror");
        view.addObject("ex", exception);
        return view;
    }

    // 解决算数异样
    @ExceptionHandler(value = { ArithmeticException.class})
    public ModelAndView handleException02(Exception exception) {System.out.println("全局的 handleException02..." + exception);
        ModelAndView view = new ModelAndView("myerror");
        view.addObject("ex", exception);
        return view;
    }
}

3. @ResponseStatus 注解异样
@ResponseStatus 注解标注在自定义异样上,用于设置自定义异样信息

@ResponseStatus(reason = "用户被回绝登录", value = HttpStatus.NOT_ACCEPTABLE)
public class UsernameNotFoundException extends RuntimeException {private static final long serialVersionUID = 1L;}

3. DefaultHandlerExceptionResolver 默认异样
DefaultHandlerExceptionResolver 蕴含以下默认异样

源码:
public class DefaultHandlerExceptionResolver extends AbstractHandlerExceptionResolver {
    ...
    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
            Object handler, Exception ex) {

        try {if (ex instanceof NoSuchRequestHandlingMethodException) {return handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException) ex, request, response,
                        handler);
            }
            else if (ex instanceof HttpRequestMethodNotSupportedException) {return handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException) ex, request,
                        response, handler);
            }
            else if (ex instanceof HttpMediaTypeNotSupportedException) {return handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException) ex, request, response,
                        handler);
            }
            else if (ex instanceof HttpMediaTypeNotAcceptableException) {return handleHttpMediaTypeNotAcceptable((HttpMediaTypeNotAcceptableException) ex, request, response,
                        handler);
            }
            else if (ex instanceof MissingPathVariableException) {return handleMissingPathVariable((MissingPathVariableException) ex, request,
                        response, handler);
            }
            else if (ex instanceof MissingServletRequestParameterException) {return handleMissingServletRequestParameter((MissingServletRequestParameterException) ex, request,
                        response, handler);
            }
            else if (ex instanceof ServletRequestBindingException) {return handleServletRequestBindingException((ServletRequestBindingException) ex, request, response,
                        handler);
            }
            else if (ex instanceof ConversionNotSupportedException) {return handleConversionNotSupported((ConversionNotSupportedException) ex, request, response, handler);
            }
            else if (ex instanceof TypeMismatchException) {return handleTypeMismatch((TypeMismatchException) ex, request, response, handler);
            }
            else if (ex instanceof HttpMessageNotReadableException) {return handleHttpMessageNotReadable((HttpMessageNotReadableException) ex, request, response, handler);
            }
            else if (ex instanceof HttpMessageNotWritableException) {return handleHttpMessageNotWritable((HttpMessageNotWritableException) ex, request, response, handler);
            }
            else if (ex instanceof MethodArgumentNotValidException) {return handleMethodArgumentNotValidException((MethodArgumentNotValidException) ex, request, response,
                        handler);
            }
            else if (ex instanceof MissingServletRequestPartException) {return handleMissingServletRequestPartException((MissingServletRequestPartException) ex, request,
                        response, handler);
            }
            else if (ex instanceof BindException) {return handleBindException((BindException) ex, request, response, handler);
            }
            else if (ex instanceof NoHandlerFoundException) {return handleNoHandlerFoundException((NoHandlerFoundException) ex, request, response, handler);
            }
        }
        catch (Exception handlerException) {if (logger.isWarnEnabled()) {logger.warn("Handling of [" + ex.getClass().getName() + "] resulted in Exception", handlerException);
            }
        }
        return null;
    }
    ...
}

如下 HttpRequestMethodNotSupportedException 申请形式不对。应用 GET 对 POST 办法进行拜访

@RequestMapping(value = "/handle03", method = RequestMethod.POST)
public String postMethod() {return "success";}

4. 没有找到对应异样解决类
若没有对应异样解决类,会进入对应服务器谬误页面

正文完
 0