SpringBoot统一异常处理

  一:在实际开发中,当我们程序报错时,不是直接显示错误内容给用户,一般都会统一跳转到错误页面。定义一个异常方法,如下:

    @RequestMapping("/exception")
    public String exception() throws Exception{
      throw new Exception("error");
    }

  显示结果如下:这是springboot提供的默认error映射页面。

  

  二:统一异常处理(返回错误页面)

  (1)创建全局异常处理类,如下:

package springboot.web;

import javax.servlet.http.HttpServletRequest;

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

@ControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e){
        ModelAndView modelAndView =new ModelAndView();
        modelAndView.addObject("exception",e);
        modelAndView.addObject("url",req.getRequestURI());
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

  使用@ControllerAdvice定义统一的异常处理类,@ExceptionHandler用来定义函数针对的异常类型,最后跳转到error.html。

   三:统一异常处理(返回json格式)

  (1)如果要返回json格式,只需要在@ExceptionHandler下新加一个@ResponseBody注解即可,如下:

    //统一返回json错误信息
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, Exception e){
        ErrorInfo<String> r = new ErrorInfo<String>();
        r.setMessage(e.getMessage());
        r.setCode(ErrorInfo.ERROR);
        r.setData("Return jsonException");
        r.setUrl(req.getRequestURI());
        return r;
    }

  (2)创建统一的Json返回对象,如下:

public class ErrorInfo <T>{

    public static final Integer OK =0;
    public static final Integer ERROR=100;
    
    private Integer code; //消息类型
    private String message;//消息内容
    private String url;//请求的url
    private T data;//请求返回的数据
    
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public T getData() {
        return data;
    }
    public void setData(T data) {
        this.data = data;
    }
    
}

  (3)启动postman,调用方法,返回如下:

  

原文地址:https://www.cnblogs.com/gdpuzxs/p/7191625.html