SpringBoot的全局异常处理
文章目录
注解@ControllerAdvice
使用 @ControllerAdvice注解类放在项目中,Spring能扫描到的地方。就可以实现全局异常的处理
注解@ExceptionHandler
捕获到异常后会进入此注解的方法中去执行具体的代码(比如跳转html界面等等操作)
具体操作
1.创建MyExceptionHandler类
import ifshop.returnMapper.ReturnMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
/**
* @Author if
* @Description:
* 使用 @ControllerAdvice,只要把这个类放在项目中,Spring能扫描到的地方。就可以实现全局异常的处理
* @Date 2021-02-13 下午 05:02
*/
@ControllerAdvice
public class MyExceptionHandler {
@Autowired
private ReturnMapper returnMapper;
/**
* 全局处理Exception
* 错误的情况下返回500
* @return
*/
@ResponseBody
@ExceptionHandler(value = {Exception.class})
public Map<String,Object> handleOtherExceptions() {
//此处可以写自己的具体的处理,以下仅示例异常时向前端返回500和说明
return returnMapper.returnMethod(500,"服务器出了点小差",null);
}
}
注意: 代码中的ReturnMapper类是我自定义的一个简单返回模板类,具体代码如下:
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* @Author if
* @Description: What is it
* @Date 2021-01-25 下午 06:35
*/
@Service
public class ReturnMapper {
/**
* 给网页url,返回int类型的状态码
* 200 (成功) 服务器已成功处理了请求。 通常,这表示服务器提供了请求的网页。
* 400 (错误请求) 服务器不理解请求的语法。(参数错误或者少了)
* 401 (无权限处理)禁止访问接口
* 404 (未找到) 服务器找不到请求的网页。
* 405 (方法禁用) 禁用请求中指定的方法。
* 500 (服务器内部错误) 服务器遇到错误,无法完成请求。
* 503 (服务正忙) 服务器目前无法使用(由于超载或停机维护)。 通常,这只是暂时状态。
* @param msg
* @param data
* @return 返回给前端code状态码、msg提示消息,data数据
*/
public Map<String,Object> returnMethod(int http,String msg,Object data){
Map<String,Object> map=new HashMap<>();
map.put("code",http);
/**
* 访问成功且有数据返回
*/
if(http == 200){
map.put("msg",msg);
map.put("data",data);
return map;
}
/**
* 404找不到网页
*/
else if(http==404){
map.put("msg","找不到该页面");
return map;
}
/**
* 401无权限操作
*/
else if(http==401){
map.put("msg","无权限操作");
return map;
}
/**
* 400,405,500访问失败
*/
else{
map.put("msg","服务器出了点小差");
return map;
}
}
}
2.Controller类编写测试接口代码
import ifshop.returnMapper.ReturnMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* @Author if
* @Description: What is it
* @Date 2021-01-25 下午 06:35
*/
@RestController
public class UserController {
@Autowired
private ReturnMapper returnMapper;
@PostMapping("testException")
public Map<String,Object> test(){
return returnMapper.returnMethod(200,"测试","测试");
}
@RequestMapping("helloTest")
public Map<String,Object> test3(){
return returnMapper.returnMethod(200,"正常访问","正常测试");
}
}
3.测试
按照正常的post访问testException接口时会正常访问用get访问testException接口时会报405
如图
但是我们编写了异常处理代码,就会交给我们的全局异常处理类来处理,而不是spring自带的处理
如图
4.总结
这只是一个很简单的全局异常处理的小例子,实际上springboot还有许多对于异常的处理机制,本博客只是对其中一个进行了示例