Java:SpringBoot统一异常处理和404异常

简介: Java:SpringBoot统一异常处理和404异常

原理

  • @ControllerAdvice + @ExceptionHandler 统一处理应用级别的异常
  • 自定义ErrorController 处理容器级别的异常,例如:404异常

统一返回格式

package com.github.mouday.common;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
 * 统一返回格式
 */
public class JsonResult implements Serializable {
    private String msg;
    private Integer code;
    private Object data;
    private JsonResult(Object data, String msg, Integer code) {
        this.data = data;
        this.msg = msg;
        this.code = code;
    }
    public static JsonResult success(Object data) {
        return new JsonResult(data, "success", 0);
    }
    public static JsonResult error() {
        return new JsonResult(null, "error", -1);
    }
    public static JsonResult error(String msg) {
        return new JsonResult(null, msg, -1);
    }
    public static JsonResult error(String msg, Integer code) {
        return new JsonResult(null, msg, code);
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }
    public Map<String, Object> toMap() {
        Map<String, Object> map = new HashMap<>();
        map.put("msg", this.msg);
        map.put("code", this.code);
        map.put("data", this.data);
        return map;
    }
}

统一异常处理

package com.github.mouday.common;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * 统一异常处理
 * 参考
 * https://www.jianshu.com/p/3998ea8b53a8
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public JsonResult exceptionHandler(Throwable error) {
        return JsonResult.error(error.getMessage(), -1);
    }
}

处理404异常

package com.github.mouday.controller;
import com.github.mouday.common.JsonResult;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
 * 处理404异常
 * <p>
 * 参考
 * https://www.cnblogs.com/54chensongxia/archive/2020/11/20/14007696.html
 * https://blog.csdn.net/qq_38571892/article/details/123395165
 */
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class CustomErrorController extends BasicErrorController {
    public CustomErrorController() {
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }
    /**
     * 覆盖默认的JSON响应
     */
    @Override
    @RequestMapping
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        if (status == HttpStatus.NO_CONTENT) {
            return new ResponseEntity<>(status);
        }
        Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        String message = (String) body.get("error");
        Map<String, Object> result = JsonResult.error(message).toMap();
        return new ResponseEntity<>(result, status);
    }
}

现在,所有接口的返回格式就统一了

{
  "msg": "服务端运行时异常",
  "code": -1,
  "data": null
}

参考

Spring Boot优雅地处理404异常

SpringBoot 统一异常处理(附核心工具类-ErrorInfoBuilder)

Spring Boot之异常处理


相关文章
|
6月前
|
安全 Java
Java异常处理:程序世界的“交通规则
Java异常处理:程序世界的“交通规则
377 98
|
6月前
|
安全 Java 编译器
驾驭Java异常处理:从新手到专家的优雅之道
驾驭Java异常处理:从新手到专家的优雅之道
313 59
|
9月前
|
Java 编译器 数据库连接
Java异常处理:写出更健壮的代码
Java异常处理:写出更健壮的代码
263 0
|
8月前
|
Java 数据库 C++
Java异常处理机制:try-catch、throws与自定义异常
本文深入解析Java异常处理机制,涵盖异常分类、try-catch-finally使用、throw与throws区别、自定义异常及最佳实践,助你写出更健壮、清晰的代码,提升Java编程能力。
|
9月前
|
Java 数据库连接 API
Java 8 + 特性及 Spring Boot 与 Hibernate 等最新技术的实操内容详解
本内容涵盖Java 8+核心语法、Spring Boot与Hibernate实操,按考试考点分类整理,含技术详解与代码示例,助力掌握最新Java技术与应用。
278 2
|
10月前
|
Java 数据库连接 API
Java 对象模型现代化实践 基于 Spring Boot 与 MyBatis Plus 的实现方案深度解析
本文介绍了基于Spring Boot与MyBatis-Plus的Java对象模型现代化实践方案。采用Spring Boot 3.1.2作为基础框架,结合MyBatis-Plus 3.5.3.1进行数据访问层实现,使用Lombok简化PO对象,MapStruct处理对象转换。文章详细讲解了数据库设计、PO对象实现、DAO层构建、业务逻辑封装以及DTO/VO转换等核心环节,提供了一个完整的现代化Java对象模型实现案例。通过分层设计和对象转换,实现了业务逻辑与数据访问的解耦,提高了代码的可维护性和扩展性。
387 1
|
10月前
|
Java 程序员 数据库连接
我们详细地讲解一下 Java 异常及要如何处理
我是小假 期待与你的下一次相遇 ~
231 1
|
10月前
|
SQL Java 数据库
解决Java Spring Boot应用中MyBatis-Plus查询问题的策略。
保持技能更新是侦探的重要素质。定期回顾最佳实践和新技术。比如,定期查看MyBatis-Plus的更新和社区的最佳做法,这样才能不断提升查询效率和性能。
569 1
下一篇
开通oss服务