Spring Boot学习——统一异常处理
本随笔记录使用Spring Boot统一处理异常。
本文实例是从数据库中根据ID查询学生信息,要求学生的年龄在14——20岁之间。小于14岁,提示“你可能在上初中”;大于20岁,提示“呢可能在上大学”。
第一步,创建枚举类ResultEnum,用来管理异常信息
package *;//自己定义
public enum ResultEnum {
UNKONW_ERROR(-1, "未知错误"),
SUCCESS(0, "成功"),
PRIMARY_SCHOOL(100, "年龄小于14岁,可能正在上中学"),
UNIVERSITY(101, "年龄大于20岁,可能正在上大学");
private Integer code;
private String msg;
ResultEnum( Integer code, String msg){
this.code = code;
this.msg = msg;
}
public Integer getCode(){
return this.code;
}
public String getMsg(){
return this.msg;
}
}
第二步,创建自己的异常类StudentException,代码如下:
package *;//自己定义
import *.ResultEnum; //自己定义路径
public class StudentException extends RuntimeException {
private Integer code;
public StudentException(ResultEnum resultEnum){
super(resultEnum.getMsg());
this.code = resultEnum.getCode();
}
public void setCode(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
}
第三步,创建返回报文实体类Result.java
package *;//自己定义 import *.Result; //自己定义的路径 /**
* HTTP请求返回处理工具类
*/
public class ResultUtil {
public static Result success(){
return success(null);
}
public static Result success(Object object){
Result result = new Result();
result.setCode(0);
result.setMsg("成功");
result.setDate(object);
return result;
} public static Result error(Integer code, String msg){
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
}
第四步,创建请求返回工具类ResultUtil.java
package *;//自己定义 import *.Result;//自己定义的路径 /**
* HTTP请求返回处理工具类
*/
public class ResultUtil {
public static Result success(){
return success(null);
}
public static Result success(Object object){
Result result = new Result();
result.setCode(0);
result.setMsg("成功");
result.setDate(object);
return result;
} public static Result error(Integer code, String msg){
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
}
第五步,创建统一处理异常的类ExceptionHandle.java,代码如下:
package *; //自己定义 import *.StudentException; //自己定义路径
import *.Result; //自己定义路径
import *.ResultUtil; //自己定义路径
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice
public class ExceptionHandle {
private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); @ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handler( Exception e){
if( e instanceof StudentException){
StudentException studentException = (StudentException) e;
return ResultUtil.error( studentException.getCode(), studentException.getMessage());
}else {
logger.info("[系统异常] {}",e);
return ResultUtil.error( -1, "未知错误");
}
}
}
第六步,在service中编写业务逻辑代码:
package *; //自己定义 import *.ResultEnum; //自己定义的路径
import *.StudentException; //自己定义的路径
import *.StudentRepository; //自己定义的路径
import *.Student; //自己定义的路径
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import javax.transaction.Transactional; @Service
public class StudentService {
@Autowired
private StudentRepository studentRepository; /**
* 根据ID查询符合条件的学生
* @param id
* @throws Exception
*/
public Student getStudentById( Integer id) throws Exception{
Student student = studentRepository.findOne(id);
Integer age = student.getAge();
if(age < 14){
throw new StudentException(ResultEnum.PRIMARY_SCHOOL);
}else if(age > 20){
throw new StudentException(ResultEnum.UNIVERSITY);
} //进行下面逻辑操作
return student;
}
}
第七步,在controller中调用service方法,代码如下:
package *; //自己定义路径 import *.Result; //自己定义路径
import *.StudentService; //自己定义路径
import *.ResultUtil; //自己定义路径
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*; import javax.validation.Valid;
import java.util.List; @RestController
public class StudentController {
@Autowired
private StudentService studentService; /**
* 根据ID查询学生
*/
@GetMapping(value = "/student/getage/{id}")
public Result getStudentById(@PathVariable("id") Integer id) throws Exception{
return ResultUtil.success(studentService.getStudentById(id));
} }
最后,使用postman访问http://127.0.0.1:8080/student/getage/1 ,查看结果。
Spring Boot学习——统一异常处理的更多相关文章
- 基于Spring Boot的统一异常处理设计
基于Spring Boot的统一异常处理设计 作者: Grey 原文地址:https://www.cnblogs.com/greyzeng/p/11733327.html Spring Boot中,支 ...
- spring boot配置统一异常处理
基于@ControllerAdvice的统一异常处理 >.这里ServerException是我自定义的异常,和普通Exception分开处理 >.这里的RequestResult是我自定 ...
- spring boot 中统一异常处理
基于 spring boot 对异常处理的不友好,现在通过其他的方式来统一处理异常 步骤一:自定义异常类 public class UserNotExistException extends Runt ...
- 基于spring boot的统一异常处理
一.springboot的默认异常处理 Spring Boot提供了一个默认的映射:/error,当处理中抛出异常之后,会转到该请求中处理,并且该请求有一个全局的错误页面用来展示异常内容. 例如这里我 ...
- Spring Boot实践——统一异常处理
注解说明 @ControllerAdvice,是Spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强.让我们先看看@ControllerAdvice的实现: /** * Special ...
- 【Spring Boot】Spring Boot之统一异常处理
一.统一异常处理的作用 在web应用中,请求处理时,出现异常是非常常见的.所以当应用出现各类异常时,进行异常的统一捕获或者二次处理(比如空指针异常或sql异常正常是不能外抛)是非常必要的,然后右统一异 ...
- spring boot 2 统一异常处理
spring mvc 针对controller层异常统一处理非常简单,使用 @RestControllerAdvice 或 @RestControllerAdvice 注解就可以轻@RestContr ...
- Spring Boot学习路线
Spring Boot 学习路线,本文计划根据作者近几年的工作.学习经验,来分析和制定一个学习使用 Spring Boot技术的步骤路线图. SpringBoot是伴随着Spring4.0诞生的: S ...
- 15 个优秀开源的 Spring Boot 学习项目,一网打尽!
Spring Boot 算是目前 Java 领域最火的技术栈了,松哥年初出版的 <Spring Boot + Vue 全栈开发实战>迄今为止已经加印了 8 次,Spring Boot 的受 ...
随机推荐
- HDU 1423 Greatest Common Increasing Subsequence(LCIS)
Greatest Common Increasing Subsequenc Problem Description This is a problem from ZOJ 2432.To make it ...
- 09.1.VUE学习之watch监听属性变化实现类百度搜索栏功能ajax异步请求数据,返回数组
09.1html里 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> < ...
- 06.VUE学习之非常实用的计算属性computed实例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http ...
- 学习pytho第五天 循环
age_of_Bob = 56#定义年龄 count = 0#头部计数 while True:#while循环 if count ==3:#如果次数==3: break#退出 guess_age = ...
- 自动发现项目中的URL,django1版本和django2版本
一.django 1 版本 routers.py import re from collections import OrderedDict from django.conf import setti ...
- POJ 3320 尺取法(基础题)
Jessica's Reading Problem Description Jessica's a very lovely girl wooed by lots of boys. Recently s ...
- Storm: 遇到问题总结
1.没有ack : kafkaspout id 重复导致每次读最新没有数据. 2.由于storm提供的读取kafka的enternal工具存在bug,导致重复读取数据,致使数据不准确.storm bu ...
- 怎么把myeclipse项目导入IDEA中
先把myeclipse下的项目拷贝到IDEA的部署目录中,把一些不用的配置文件删除,只留下一个干净的项目 打开IDEA,点击import Project,引入一个项目,选择IDEA部署目录下刚拷贝过去 ...
- [原]sencha touch之carousel
carousel组件是个非常不错的东东,自带可滑动的效果,效果如下图 上面部分可以左右滑动,下面部分可以上下滑动,效果还是不错的,app程序中很有用的布局 代码如下: Ext.application( ...
- Js中的undefined和not defined
1.undefined 已经声明,但未赋值 2.not defined 未声明,报错