欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

详解SpringMVC中的异常处理

时间:2022-09-18 11:12:28|栏目:JAVA代码|点击:

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

4. 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";
}

5. 没有找到对应异常处理类

若没有对应异常处理类,会进入对应服务器错误页面

上一篇:剑指Offer之Java算法习题精讲数组与字符和等差数列

栏    目:JAVA代码

下一篇:java9新特性Collection集合类的增强与优化方法示例

本文标题:详解SpringMVC中的异常处理

本文地址:http://www.codeinn.net/misctech/213971.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有