目标:springboot全局异常捕获
概述
1、自定义异常处理
package com.itheima.exeception;
/**
* @Author David老师
* @Description
* @Tel/微信:*****
* @Version 1.0
**/
public class BussinssException extends RuntimeException {
private String code;
private String msg;
public BussinssException(String code,String msg){
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
2:自定义异常
package com.itheima.exeception;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
/**
* @Author David老师
* @Description
* @Tel/微信:150******37
* @Version 1.0
**/
@ControllerAdvice
public class MyControllerAdvice {
/*
* @Author David老师
* @Tel/微信:150****37
* @Description 所有的全局异常,只要作用在@RequestMapping方法上,所有的异常信息都会被捕获到。
* @Date 16:57 2019/5/29
* @Param [ex]
* @return java.util.Map
**/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Map errorHandler( Exception ex){
Map map = new HashMap<>();
map.put("code",-1);
map.put("msg",ex.getMessage());
return map;
}
@ResponseBody
@ExceptionHandler(value = BussinssException.class)
public Map errorHandler2( BussinssException ex){
Map map = new HashMap<>();
map.put("code",ex.getCode());
map.put("msg",ex.getMsg());
return map;
}
}
3:UserServiceImpl
@Override
@Transactional
public int saveUser(User user) {
try{
return userDao.saveUser(user);//取钱
}catch(Exception ex){
throw new BussinssException("409","保存用户失败,请检查");
}
}
测试
package com.itheima.web;
import com.itheima.exeception.BussinssException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
/**
* @Author David老师
* @Description
* @Tel/微信:150*****37
* @Version 1.0
**/
@RestController
public class UserController {
@Autowired
private IUserService userService;
/**
* 保存用户
* @param user
*/
@PostMapping("/saveUser")
public int saveUser(User user){
return userService.saveUser(user);
}
}
使用postman访问:
http://localhost:8081/saveUser?username=zhangsan&password=23w4e5r65t7y8
回复关键词
JUC 分布式限流 消息队列 alibaba JVM性能调优 Docker
看更多精彩教程
别忘了点个在看哦!转发那就太好了!
![2640075c3640676c2a9237058e554a8f.png](https://i-blog.csdnimg.cn/blog_migrate/44d243e15d253da6c55f232cbb1340b7.png)