异常处理:

当controller中方法在执行过程中如果出现异常,我们应该如何处理异常这种方式,称之为异常处理。

1、传统方式开发异常处理

HandlerExceptionResolver 处理异常解析类

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//传统方式处理异常以及自定义异常
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver
{
    //resolveException:当Controller中任意一个方法出现异常时,如果该控制器的方法没有自己处理异常(try catch),则会进入此方法
    //参数一 request:当前请求对象
    //参数二 response:当前请求对应响应对象
    //参数三 o:当前出现错误的方法对象
    //参数四 e:出现的异常对象
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)
    {
        ModelAndView modelAndView = new ModelAndView();
        if(e instanceof MyException)
        {
            modelAndView.setViewName("MyException.html");
        }
        else
        {
            modelAndView.setViewName("500.html");
        }
        return modelAndView;
    }
}


//自定义异常
public class MyException extends RuntimeException
{
    public MyException()
    {
    }

    public MyException(String message)
    {
        super(message);
    }
}

  

2、前后端分离开发异常处理

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler
{

    //处理指定异常
    @ExceptionHandler(value = MyException.class)        //就近原则,会先处理此异常而不是Exception
    @ResponseBody
    public ResponseEntity<String> myExceptionHandler(MyException mE)
    {
        return new ResponseEntity<String>(mE.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    //处理所有异常
    @ExceptionHandler(value = Exception.class)      //用在方法上,作用:用来处理异常   value属性:指定处理的异常类型
    @ResponseBody
    public ResponseEntity<String> exceptionHandler(Exception e)
    {
        return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }


}

  

 

posted on 2021-08-24 17:06  baihuntun  阅读(165)  评论(0)    收藏  举报