import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
-
@author guozhengMu
-
@version 1.0
-
@date 2019/8/21 14:55
-
@description
-
@modify
*/
@RestController
@RequestMapping(value = “/test”, method = RequestMethod.GET)
public class TestController {
@RequestMapping(“/json”)
public JSONObject test() {
JSONObject result = new JSONObject();
try {
// 业务逻辑代码
result.put(“code”, 0);
result.put(“msg”, “操作成功!”);
result.put(“data”, “测试数据”);
} catch (Exception e) {
result.put(“code”, 500);
result.put(“msg”, “系统异常,请联系管理员!”);
}
return result;
}
}
这样的话,每个接口都这样处理,非常麻烦,需要一种更优雅的实现方式
2.1 定义统一的JSON结构
===============
统一的 JSON 结构中属性包括数据、状态码、提示信息,其他项可以自己根据需要添加。一般来说,应该有默认的返回结构,也应该有用户指定的返回结构。由于返回数据类型无法确定,需要使用泛型,代码如下:
public class ResponseInfo {
/**
- 状态码
*/
protected String code;
/**
- 响应信息
*/
protected String msg;
/**
- 返回数据
*/
private T data;
/**
- 若没有数据返回,默认状态码为 0,提示信息为“操作成功!”
*/
public ResponseInfo() {
this.code = 0;
this.msg = “操作成功!”;
}
/**
-
若没有数据返回,可以人为指定状态码和提示信息
-
@param code
-
@param msg
*/
public ResponseInfo(String code, String msg) {
this.code = code;
this.msg = msg;
}
/**
-
有数据返回时,状态码为 0,默认提示信息为“操作成功!”
-
@param data
*/
public ResponseInfo(T data) {
this.data = data;
this.code = 0;
this.msg = “操作成功!”;
}
/**
-
有数据返回,状态码为 0,人为指定提示信息
-
@param data
-
@param msg
*/
public ResponseInfo(T data, String msg) {
this.data = data;
this.code = 0;
this.msg = msg;
}
// 省略 get 和 set 方法
}
2.2 使用统一的JSON结构
===============
我们封装了统一的返回数据结构后,在接口中就可以直接使用了。如下:
import com.example.demo.model.ResponseInfo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
-
@author guozhengMu
-
@version 1.0
-
@date 2019/8/21 14:55
-
@description
-
@modify
*/
@RestController
@RequestMapping(value = “/test”, method = RequestMethod.GET)
public class TestController {
@RequestMapping(“/json”)
public ResponseInfo test() {
try {
// 模拟异常业务代码
int num = 1 / 0;
return new ResponseInfo(“测试数据”);
} catch (Exception e) {
return new ResponseInfo(500, “系统异常,请联系管理员!”);
}
}
}
如上,接口的返回数据处理便优雅了许多。针对上面接口做个测试,启动项目,通过浏览器访问:localhost:8096/test/json,得到响应结果:
{“code”:500,“msg”:“系统异常,请联系管理员!”,“data”:null}
3 全局异常处理
========
3.1 系统定义异常处理
============
新建一个 ExceptionHandlerAdvice 全局异常处理类,然后加上 @RestControllerAdvice 注解即可拦截项目中抛出的异常,如下代码中包含了几个异常处理,如参数格式异常、参数缺失、系统异常等,见下例:
@RestControllerAdvice
@Slf4j
public class ExceptionHandlerAdvice {
// 参数格式异常处理
@ExceptionHandler({IllegalArgumentException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseInfo badRequestException(IllegalArgumentException exception) {
log.error(“参数格式不合法:” + e.getMessage());
return new ResponseInfo(HttpStatus.BAD_REQUEST.value() + “”, “参数格式不符!”);
}
// 权限不足异常处理
@ExceptionHandler({AccessDeniedException.class})
@ResponseStatus(HttpStatus.FORBIDDEN)
public ResponseInfo badRequestException(AccessDeniedException exception) {
return new ResponseInfo(HttpStatus.FORBIDDEN.value() + “”, exception.getMessage());
}
// 参数缺失异常处理
@ExceptionHandler({MissingServletRequestParameterException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseInfo badRequestException(Exception exception) {
return new ResponseInfo(HttpStatus.BAD_REQUEST.value() + “”, “缺少必填参数!”);
}
// 空指针异常
@ExceptionHandler(NullPointerException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseInfo handleTypeMismatchException(NullPointerException ex) {
log.error(“空指针异常,{}”, ex.getMessage());
return new JsonResult(“500”, “空指针异常”);
}
@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public JsonResult handleUnexpectedServer(Exception ex) {
log.error(“系统异常:”, ex);
return new JsonResult(“500”, “系统发生异常,请联系管理员”);
}
// 系统异常处理
先自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《Java开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以扫码领取!
![img](https://i-blog.csdnimg.cn/blog_migrate/912ec54749c84ac5401d13cf7862a279.jpeg)
最后
金三银四到了,送上一个小福利!
4eRkbs-1711456842797)]
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以扫码领取!
![img](https://i-blog.csdnimg.cn/blog_migrate/912ec54749c84ac5401d13cf7862a279.jpeg)
最后
金三银四到了,送上一个小福利!
[外链图片转存中…(img-tMN4H5ZJ-1711456842797)]
[外链图片转存中…(img-2ZVCDIAI-1711456842798)]
[外链图片转存中…(img-InEe8vK0-1711456842798)]
需要更多Java资料的小伙伴可以帮忙点赞+关注,点击传送门,即可免费领取!