springboot取消全局返回
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot取消全局返回相关的知识,希望对你有一定的参考价值。
参考技术A 1.1 使用字符串返回@GetMapping("/getUserName")
public String getUserName()
return "HuaGe";
调用接口返回结果:
HuaGe
1.2 使用实体类返回
@GetMapping("/getUserName")
public User getUserName()
return new User("HuaGe",18,"男");
调用接口返回结果:
"name": "HuaGe",
"age": "18",
"性别": "男",
1.3 异常情况下返回
@GetMapping("/getUserName")
public static String getUserName()
HashMap hashMap = Maps.newHashMap();
return hashMap.get(0).toString();
Java SpringBoot全局错误处理类,返回标准结果
package demo.utils; import com.alibaba.fastjson.JSON; import demo.controller.ProductController; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; /** * Controller全局错误捕获类 */ @RestControllerAdvice //拦截异常并统一处理 public class ExceptionIntercept { public static final String PLAT_ERROR = "PLAT_ERROR"; // Logger和LogManager导入的是org.apache.logging包 private static final Logger logger = LogManager.getLogger(ProductController.class); @ExceptionHandler(Exception.class) public MessagePack handler(Exception ex) { //返回错误数据包 MessagePack pack = new MessagePack(); pack.setCode(MessagePack.ERROR); pack.setMessage(ex.getMessage()); pack.setStatus(PLAT_ERROR); //同时记录错误日志 logger.error("Controller全局错误捕获类==>" + JSON.toJSONString(pack)); return pack; } }
package demo.utils; import java.io.Serializable; /** * 统一返回消息类 */ public class MessagePack implements Serializable { public static final long OK = 0; public static final long ERROR = -1; // 状态码 private long code; // 信息 private String message; // 携带的值 private Object object; // 状态信息 private String status; public long getCode() { return code; } public void setCode(long code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
以上是关于springboot取消全局返回的主要内容,如果未能解决你的问题,请参考以下文章
助力SpringBoot自动配置的条件注解ConditionalOnXXX分析--SpringBoo
Swagger2 常用使用 及 SpringBoo 整合 Swagger2