spring boot快速入门 8: 异常处理
异常处理简单样例:
第一步:创建result实体类
package com.payease.domain; /**
* http请求返回的最外层对象
* Created by liuxiaoming on 2017/11/7.
*/
public class Result<T> { /** 错误码 */
private Integer code; /** 提示信息 */
private String msg; /** 具体内容 */
private T data; public Integer getCode() {
return code;
} public void setCode(Integer code) {
this.code = code;
} public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
} public T getData() {
return data;
} public void setData(T data) {
this.data = data;
}
}
第二步:创建resultUtil工具类
package com.payease.utils; import com.payease.domain.Result; /**
* 对于结果集(Result)的工具类
* Created by liuxiaoming on 2017/11/7.
*/
public class ResultUtil {
public static Result success(Object object){
Result result = new Result();
result.setCode(0);
result.setMsg("成功");
result.setData(object);
return result;
} public static Result success(){
return success(null);
} public static Result error(Integer code,String msg){
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
} }
第三步:在controller中调用
@Autowired
private GirlRespository girlRespository; /**
* 创建一个女生
*/
@PostMapping("/girls")
public Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult){
Result result = new Result();
if(bindingResult.hasErrors()){
return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage());
}
girl.setCupSize(girl.getCupSize());
girl.setAge(girl.getAge());
return ResultUtil.success(girlRespository.save(girl));
}
第四步:启动项目 在postman中提交请求
请求成功:

请求失败:

样例:统一异常处理

第一步:创建枚举类ResultEnum(统一管理错误码和错误信息)
package com.payease.enums; /**
* Created by liuxiaoming on 2017/11/7.
*/
public enum ResultEnum {
UNKNOWN_ERROR(-1, "未知错误"),
SUCCESS(0, "成功"),
PRIMARY_SCHOOL(100,"你可能还在上小学"),
MIDDLE_SCHOOL(101,"你可能在上初中"), ; private Integer code;
private String msg; ResultEnum(Integer code, String msg){
this.code = code;
this.msg = msg;
} public Integer getCode() {
return code;
} public void setCode(Integer code) {
this.code = code;
} public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
}
}
第二步:创建自定义异常捕获类ExceptionHandle
package com.payease.handle; import com.payease.domain.Result;
import com.payease.enums.ResultEnum;
import com.payease.exception.GirlException;
import com.payease.utils.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; /**
* 自定义异常捕获类
* Created by liuxiaoming on 2017/11/7.
*/
@ControllerAdvice
public class ExceptionHandle { //日志
private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); @ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e){
if(e instanceof GirlException){
GirlException girlException = (GirlException)e;
return ResultUtil.error(girlException.getCode(),girlException.getMessage());
}else{
logger.info("【系统异常】{}",e);
return ResultUtil.error(ResultEnum.UNKNOWN_ERROR.getCode(),ResultEnum.UNKNOWN_ERROR.getMsg());
//return ResultUtil.error(-1,"未知错误:");
} }
}
第三步:创建自定义异常类
package com.payease.exception; import com.payease.enums.ResultEnum; /**
* 自定义异常
* Created by liuxiaoming on 2017/11/7.
*/
public class GirlException extends RuntimeException{ private Integer code; public GirlException(ResultEnum resultEnum) {
super(resultEnum.getMsg());
this.code = resultEnum.getCode();
} public Integer getCode() {
return code;
} public void setCode(Integer code) {
this.code = code;
}
}
第四步:在service中添加方法
public void getAge(Integer id) throws Exception{
Girl girl = girlRespository.findOne(id);
Integer age = girl.getAge();
if(age < 10){
//返回 "你还在上小学吧" code=100
throw new GirlException(ResultEnum.PRIMARY_SCHOOL);
}else if(age > 10 && age < 16){
//返回 "你可能在上初中" code=101
throw new GirlException(ResultEnum.MIDDLE_SCHOOL);
}
//如果>16岁,加钱
//...
}
第五步:在controller中调用该方法
/**
* 通过ID判断该女生年龄是否符合要求
* @param id
* @throws Exception
*/
@GetMapping("girls/getAge/{id}")
public void getAge(@PathVariable("id")Integer id) throws Exception{ girlService.getAge(id);
}
第六步:启动项目 postman提交

spring boot快速入门 8: 异常处理的更多相关文章
- Spring Boot 快速入门
Spring Boot 快速入门 http://blog.csdn.net/xiaoyu411502/article/details/47864969 今天给大家介绍一下Spring Boot MVC ...
- Spring Boot快速入门(二):http请求
原文地址:https://lierabbit.cn/articles/4 一.准备 postman:一个接口测试工具 创建一个新工程 选择web 不会的请看Spring Boot快速入门(一):Hel ...
- spring boot入门教程——Spring Boot快速入门指南
Spring Boot已成为当今最流行的微服务开发框架,本文是如何使用Spring Boot快速开始Web微服务开发的指南,我们将使创建一个可运行的包含内嵌Web容器(默认使用的是Tomcat)的可运 ...
- Spring Boot 快速入门 史上最简单
1.Spring Boot 概述 Spring Boot 是所有基于 Spring 开发的项目的起点.Spring Boot 的设计是为了让你尽可能快的跑起来 Spring 应用程序并且尽可能减少你的 ...
- Spring Boot 快速入门(IDEA)
从字面理解,Boot是引导的意思,因此SpringBoot帮助开发者快速搭建Spring框架:SpringBoot帮助开发者快速启动一个Web容器:SpringBoot继承了原有Spring框架的优秀 ...
- 笔记61 Spring Boot快速入门(一)
IDEA+Spring Boot快速搭建 一.IDEA创建项目 略 项目创建成功后在resources包下,属性文件application.properties中,把数据库连接属性加上,同时可以设置服 ...
- Spring Boot 快速入门笔记
Spirng boot笔记 简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发 ...
- Spring Boot快速入门(最新)
本章通过完成Spring Boot基础项目的构建并实现一个简单的Http请求处理,让大家对Spring Boot有一个初步的了解,并体验其结构简单.开发快速的特性.预计阅读及演练过程将花费约5分钟. ...
- Spring Boot 快速入门(一)
简介 相信很多人都接触spring框架很长时间了,每次搭建spring框架的时候都需要配置好多的jar.xml,做很多繁琐重复的配置,稍微不留神就会出现各种各样的问题,每次调试真的是香菇.蓝瘦啊. ...
随机推荐
- 我的border能自定义四角之border-radius : 左上角,右上角,左下角,右下角。
1 边框:border: 1px solid #0081df; 2 想要单独加上四个圆角: border-bottom-left-radius: 5px; border-top-left-radius ...
- CodeForces 686A Free Ice Cream (水题模拟)
题意:给定初始数量的冰激凌,然后n个操作,如果是“+”,那么数量就会增加,如果是“-”,如果现有的数量大于等于要减的数量,那么就减掉,如果小于, 那么孩子就会离家.问你最后剩下多少冰激凌,和出走的孩子 ...
- tomcat服务器输入localhost可以访问,ip无法访问解决办法
最近在开发项目中,遇到的一个问题是: 在 tomcat中发布一个web项目,但是发布成功后,只能用http://localhost:8080/fm访问项目,不能用 http://127.0.0.1:8 ...
- swift学习之Label
//UILabel的使用方法 let label:UILabel = UILabel(frame: CGRect(x: 0, y: 100, width: view. ...
- Linux 基础教程 44-history命令
什么是history 在Linux系统日积月累的使用中,我们会输入很多命令.而在我们想重复上一个命令时,通过使用方向键向上翻就可以查看我们已经输入和使用过的命令.那大家有没有想过这个命令保存在 ...
- windows下 git+tortoiseGit的使用【转】
一定要自己写出来才能牢记,所以我来写一下 git确实比svn好用的多了,最起码只有一个文件夹用来标记版本信息比svn所有文件夹下都要放一个文件夹来标记版本信息先进多了,不然你不想要版本管理这些文件的时 ...
- python实现注册登录小程序
用python 实现模拟注册和登录的程序:用户信息最终以字典的格式储存在一个txt文件里,具体实现如下: users.txt里用户字典格式如下: { '}, '}, '} } # 注册 f = ope ...
- leetcode 合并两个有序数组
给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组. 说明: - 初始化 nums1 和 nums2 的元素数量分别为 m 和 ...
- AcWing 143. 最大异或对
https://www.acwing.com/problem/content/145 #include <iostream> #include <algorithm> usin ...
- Zipper(动态规划)
点击打开链接 描述 Given three strings, you are to determine whether the third string can be formed by combin ...