惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Help Net Security
Help Net Security
G
Google Developers Blog
雷峰网
雷峰网
WordPress大学
WordPress大学
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Engineering at Meta
Engineering at Meta
Security Latest
Security Latest
T
Threat Research - Cisco Blogs
AWS News Blog
AWS News Blog
F
Full Disclosure
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Exploit Database - CXSecurity.com
J
Java Code Geeks
U
Unit 42
C
Cyber Attacks, Cyber Crime and Cyber Security
V
V2EX
C
Cisco Blogs
博客园 - 司徒正美
Project Zero
Project Zero
L
LINUX DO - 热门话题
阮一峰的网络日志
阮一峰的网络日志
Blog — PlanetScale
Blog — PlanetScale
Scott Helme
Scott Helme
A
About on SuperTechFans
Hugging Face - Blog
Hugging Face - Blog
S
Securelist
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
G
GRAHAM CLULEY
酷 壳 – CoolShell
酷 壳 – CoolShell
Cyberwarzone
Cyberwarzone
MongoDB | Blog
MongoDB | Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 叶小钗
T
Threatpost
Recorded Future
Recorded Future
C
CXSECURITY Database RSS Feed - CXSecurity.com
宝玉的分享
宝玉的分享
N
News and Events Feed by Topic
人人都是产品经理
人人都是产品经理
The Register - Security
The Register - Security
S
Security Archives - TechRepublic
博客园 - Franky
N
News | PayPal Newsroom
Simon Willison's Weblog
Simon Willison's Weblog
S
SegmentFault 最新的问题
W
WeLiveSecurity
A
Arctic Wolf
B
Blog

博客园 - TopCoder.NET

内存操作的几个函数 Windows消息目录 映射网络驱动器命令 均值、中位数、众数 修改Android 界面颜色 设置Android程序图标和程序标题 Android中的EditText默认时不弹出软键盘的方法 UTF-8的BOM含义 详解BOM头以及去掉BOM头的方法 2017年总结 Unknown SSL protocol error in connection to xxx:443 - TopCoder.NET springmvc请求参数获取的几种方法 - TopCoder.NET 苹果手机输入中文不会触发onkeyup事件 LVS负载均衡DR模式部署 pycharm激活 Mac 终端命令行颜色高亮显示 windows7环境下使用pip安装MySQLdb python 国内镜像 mui 单页面下拉刷新 - TopCoder.NET
解决spring boot中rest接口404,500等错误返回统一的json格式
TopCoder.NET · 2018-01-28 · via 博客园 - TopCoder.NET

在开发rest接口时,我们往往会定义统一的返回格式,列如:

{
  "status": true,
  "code": 200,
  "message": null,
  "data": [
    {
      "id": "101",
      "name": "jack"
    },
    {
      "id": "102",
      "name": "jason"
    }
  ]
}

但是如果调用方请求我们的api时把接口地址写错了,就会得到一个404错误,在传统的web系统中我们可自定义404错误页面,展示更友好。

在spring boot中其实也是返回了一个json格式的数据,如下:

{
  "timestamp": 1492063521109,
  "status": 404,
  "error": "Not Found",
  "message": "No message available",
  "path": "/rest11/auth"
}

告诉我们哪个地址是没找到,其实也挺友好的,但是因为我们上面自定义的数据格式跟下面的不一致,当用户拿到这个返回的时候是无法识别的,其中最明显的是status字段。

我们自定义的是boolean类型,表示是否成功

这边返回的就是http的状态码

所以我们需要在发生这种系统错误时也能返回我们自定义的那种格式

定义一个异常处理类

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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 GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 系统异常处理,比如:404,500
     * @param req
     * @param resp
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseData defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        logger.error("", e);
        ResponseData r = new ResponseData();
        r.setMessage(e.getMessage());
        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
             r.setCode(404);
        } else {
             r.setCode(500);
        }
        r.setData(null);
        r.setStatus(false);
        return r;
    }
}

ResponseData是我们返回格式的实体类

这种在发生错误时这边会捕获到,然后封装好返回格式,返回给调用方

最后关键的一步是在spring boot的配置文件中加上如下配置:

#出现错误时, 直接抛出异常
spring.mvc.throw-exception-if-no-handler-found=true
#不要为我们工程中的资源文件建立映射
spring.resources.add-mappings=false

然后我们调用一个不存在的接口时,返回的错误信息就是我们自定义的那种格式了

{
  "status": false,
  "code": 404,
  "message": "No handler found for GET /rest11/auth",
  "data": null
}