异常处理简单样例:

第一步:创建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: 异常处理的更多相关文章

  1. Spring Boot 快速入门

    Spring Boot 快速入门 http://blog.csdn.net/xiaoyu411502/article/details/47864969 今天给大家介绍一下Spring Boot MVC ...

  2. Spring Boot快速入门(二):http请求

    原文地址:https://lierabbit.cn/articles/4 一.准备 postman:一个接口测试工具 创建一个新工程 选择web 不会的请看Spring Boot快速入门(一):Hel ...

  3. spring boot入门教程——Spring Boot快速入门指南

    Spring Boot已成为当今最流行的微服务开发框架,本文是如何使用Spring Boot快速开始Web微服务开发的指南,我们将使创建一个可运行的包含内嵌Web容器(默认使用的是Tomcat)的可运 ...

  4. Spring Boot 快速入门 史上最简单

    1.Spring Boot 概述 Spring Boot 是所有基于 Spring 开发的项目的起点.Spring Boot 的设计是为了让你尽可能快的跑起来 Spring 应用程序并且尽可能减少你的 ...

  5. Spring Boot 快速入门(IDEA)

    从字面理解,Boot是引导的意思,因此SpringBoot帮助开发者快速搭建Spring框架:SpringBoot帮助开发者快速启动一个Web容器:SpringBoot继承了原有Spring框架的优秀 ...

  6. 笔记61 Spring Boot快速入门(一)

    IDEA+Spring Boot快速搭建 一.IDEA创建项目 略 项目创建成功后在resources包下,属性文件application.properties中,把数据库连接属性加上,同时可以设置服 ...

  7. Spring Boot 快速入门笔记

    Spirng boot笔记 简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发 ...

  8. Spring Boot快速入门(最新)

    本章通过完成Spring Boot基础项目的构建并实现一个简单的Http请求处理,让大家对Spring Boot有一个初步的了解,并体验其结构简单.开发快速的特性.预计阅读及演练过程将花费约5分钟. ...

  9. Spring Boot 快速入门(一)

    简介  相信很多人都接触spring框架很长时间了,每次搭建spring框架的时候都需要配置好多的jar.xml,做很多繁琐重复的配置,稍微不留神就会出现各种各样的问题,每次调试真的是香菇.蓝瘦啊. ...

随机推荐

  1. 前端福利之HTML5 UTF-8 中文乱码(转)

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  2. HITS

    HITS 1 概述 HITS(hypertext induced topic search)超链接归纳主题搜索是由kleinbers在90年代提出的基于链接分析的网页排名算法.Hits算法是利用Hub ...

  3. linux计划任务(一)

    一次性计划任务 at /etc/init.d/atd [root@localhost ~]# at : at> /bin/ls /etc |wc -l > /tmp/yimiao_demo ...

  4. Unity3d之Coroutine

    在Unity3d中使用C#时,Coroutine是一个大有用处的好东西,至于怎么用网上多的是讲,我仅在此记录最近一次使用中的小发现. 因为某种需求,要在一个Coroutine实现中使用while循环, ...

  5. WebApi 插件式构建方案:发现并加载程序集

    插件式的 WebApi 开发,首要面对的问题就是程序集的发现.因为开发的过程中,都是在各自的解决方案下进行开发,部署后是分模块放在一个整体的的运行时网站下. 约定 这里我根据上一节的设定,把插件打包完 ...

  6. 在Windows Server 2008上部署免费的https证书

    背景 后web时代,https加密的重要性不言而喻.主流浏览器均对http站点标记不安全,敦促web服务提供商尽快升级至https. 原先的https证书多由各大域名服务商提供,动辄成千上万的部署证书 ...

  7. 杭州.Net 相关大公司,希望对大家有帮助

    本人目前大四,还在实习.北京工作辞职后,打算回杭州看看.发现杭州的大公司相对北京好少啊,招.Net相关的公司就更少了... (我认为刚毕业生还是去大公司比较靠谱,一方面也是实力的体现)大学生,而且之前 ...

  8. 【C#】在datatable中添加一序号列,编号从1依次递增,并且在第一列

    详细链接:https://shop499704308.taobao.com/?spm=a1z38n.10677092.card.11.594c1debsAGeak/// <summary> ...

  9. Mac下su命令提示su:Sorry的解决办法

    用 sudo su - 输入密码,获得root权限

  10. “全栈2019”Java异常第十八章:Exception详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java异 ...