SpringBoot自定义异常处理

阅读量: 97 编辑

SpringBoot自定义异常处理

一、自定义异常捕获

  • 1、创建一个异常捕获类

  • 2、使用@ControllerAdvice:给所有Controller控制层增加统一处理

  • 3、捕获异常之后的处理函数。添加捕获异常类型:@ExceptionHandler(value = Exception.class)

二、代码

1、创建异常捕获类

S22ExceptionHandler.java

package com.qicong.sboot.s22;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * User: 祁大聪
 */
@ControllerAdvice
public class S22ExceptionHandler {

    //异常的处理
    @ExceptionHandler(value = Exception.class)
    public Object exceptionHandler(HttpServletRequest request,
                                   HttpServletResponse response,
                                   Exception e) throws Exception{

        ModelAndView mv = new ModelAndView("error/500");
        mv.addObject("message",e);
        mv.addObject("url",request.getRequestURL());
        return mv;
    }

}

2、用于测试的Controller

S22Controller.java

package com.qicong.sboot.s22;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * User: 祁大聪
 */
@Controller
@RequestMapping("s22")
public class S22Controller {

    @RequestMapping("index")
    @ResponseBody
    public String index(){

        int i = 1/0;

        return "success";
    }
}