开发中一般常常需要使用try catch来处理异常,使用全局异常,只需要在项目开发初期设置一次,之后就都不需要手动处理异常
初期准备
使用Spring脚手架快速构建一个SpringBoot的Web项目
代码编写
准备一个返回给前端的类
public class MyResponse {
private boolean ret;
private String detail;
private Object content;
public boolean isRet() {
return ret;
}
public void setRet(boolean ret) {
this.ret = ret;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Object getContent() {
return content;
}
public void setContent(Object content) {
this.content = content;
}
public static MyResponse getErrorResp(){
MyResponse resp = new MyResponse();
resp.setRet(false);
resp.setDetail("file");
return resp;
}
public static MyResponse getErrorResp(String detail){
MyResponse resp = new MyResponse();
resp.setRet(false);
resp.setDetail(detail);
return resp;
}
public static MyResponse getSuccess(){
MyResponse resp = new MyResponse();
resp.setRet(true);
resp.setDetail("success");
return resp;
}
public static MyResponse getSuccess(Object obj){
MyResponse resp = new MyResponse();
resp.setRet(true);
resp.setDetail("success");
resp.setContent(obj);
return resp;
}
}
关键,全局异常处理类
@RestControllerAdvice
public class MyException {
private static Logger logger = LoggerFactory.getLogger(MyException.class);
@ExceptionHandler(value = Exception.class)
public MyResponse exceptionHandler(Exception e){
logger.error("错误原因:",e);
return MyResponse.getErrorResp(e.getMessage());
}
}
编写Controller和Service层,进行简单测试
controller层
@RestController
public class HomePageController {
@Autowired
private GetUser getUser;
@GetMapping("user/{id}")
public MyResponse getUser(@PathVariable String id, @RequestBody Map<String,Object> map) throws Exception {
String username=String.valueOf(map.get("username"));
return getUser.invoke(username,id);
}
}
service层
@Service
public class GetUser {
public MyResponse invoke(String username,String id) throws Exception {
if(!username.equals("admin")){
throw new Exception("登录用户不是管理员");
}
if(!id.equals("1")){
throw new Exception("不存在此用户");
}
User user = new User();
user.setId(id);
user.setUsername("张三");
return MyResponse.getSuccess(user);
}
}
万能的实体类User
public class User {
private String id;
private String username;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
启动项目,开始测试