对于一些运行时异常,由于系统出现一些未知异常时,不可能直接将报错信息返回给用户看,所以在系统中需要一个统一处理异常的地方,当程序出现异常时全局异常处理将会捕捉到异常随后执行返回统一的错误结果
代码如下
package com.xzl.website.config;
import com.xzl.website.entity.vo.ResultVo;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 统一异常处理类
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResultVo error(Exception e){
e.printStackTrace();
System.out.println("执行了全局异常处理了");
//这里返回自己定义的统一返回值
return ResultVo.fail("系统异常,请联系客服!");
}
}