关于java:四SpringMVC异常处理

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. 没有找到对应异样解决类
若没有对应异样解决类,会进入对应服务器谬误页面

【腾讯云】云产品限时秒杀,爆款1核2G云服务器,首年50元

阿里云限时活动-2核2G-5M带宽-60G SSD-1000G月流量 ,特惠价99元/年(原价1234.2元/年,可以直接买3年),速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表评论

您的电子邮箱地址不会被公开。

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据