博客
关于我
SpringBoot全局统一异常处理(包含404错误处理)
阅读量:342 次
发布时间:2019-03-04

本文共 1889 字,大约阅读时间需要 6 分钟。

Spring Boot 全局统一异常处理(包含404错误处理)

ControllerAdvice 和 ExceptionHandler 处理异常

在 Spring Boot 应用中,统一异常处理是开发中不可或缺的一部分。通过 ControllerAdviceExceptionHandler,我们可以在整个应用中实现异常的全局处理,提升系统的健壮性和用户体验。

以下是示例代码,展示了如何在 NullPointerException 上下文中使用 ExceptionHandler

package com.lius.handlers;import java.util.HashMap;import java.util.Map;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestControllerAdvice;@RestControllerAdvice(basePackages = "com.lius.controllers")public class HandlerException {    @ExceptionHandler(NullPointerException.class)    @ResponseBody    public Map
handlerNullPointerException() { Map
response = new HashMap<>(); response.put("code", 500); response.put("message", "代码错误:空指针异常!"); return response; }}

ErrorController 处理404异常

除了普通的异常处理,Spring Boot 还允许我们自定义处理 404 错误等常见 HTTP 错误。通过实现 ErrorController 接口,我们可以在 URL 映射中自定义错误页面。

以下是实现 404 错误处理的示例代码:

package com.lius.controllers;import java.util.HashMap;import java.util.Map;import org.springframework.boot.web.servlet.error.ErrorController;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class ErrorController implements ErrorController {    @Override    public String getErrorPath() {        return "/404";    }    @RequestMapping("/404")    @ResponseBody    public Map
handler404() { Map
response = new HashMap<>(); response.put("code", 404); response.put("message", "404 页面未找到!"); return response; }}

通过以上配置,我们可以在应用中实现对 404 错误的统一处理,返回指定的 JSON 格式响应,提升 API 的稳定性。

总结

通过 ControllerAdviceExceptionHandler,我们可以实现对应用中所有异常的全局处理。在处理 404 错误时,自定义错误页面可以提升用户体验和系统的美观度。

转载地址:http://innq.baihongyu.com/

你可能感兴趣的文章
Objective-C实现cycle sort循环排序算法(附完整源码)
查看>>
Objective-C实现data transformations数据转换算法(附完整源码)
查看>>
Objective-C实现datamatrix二维码识别 (附完整源码)
查看>>
Objective-C实现DateToDay 方法算法(附完整源码)
查看>>
Objective-C实现DBSCAN聚类算法(附完整源码)
查看>>
Objective-C实现DBSCAN聚类算法(附完整源码)
查看>>
Objective-C实现decision tree决策树算法(附完整源码)
查看>>
Objective-C实现degreeToRadian度到弧度算法(附完整源码)
查看>>
Objective-C实现depth first search深度优先搜索算法(附完整源码)
查看>>
Objective-C实现DES和3DES加解密算法(附完整源码)
查看>>
Objective-C实现des文件加密算法(附完整源码)
查看>>
Objective-C实现detectDirectedCycle检测定向循环算法(附完整源码)
查看>>
Objective-C实现detectUndirectedCycle检测无向循环算法(附完整源码)
查看>>
Objective-C实现deutsch jozsa算法(附完整源码)
查看>>
Objective-C实现DFS判断是否是二分图Bipartite算法(附完整源码)
查看>>
Objective-C实现DFS遍历或搜索图数据结构算法(附完整源码)
查看>>
Objective-C实现Diffie-Hellman算法(附完整源码)
查看>>
Objective-C实现Diffie—Hellman密钥交换(附完整源码)
查看>>
Objective-C实现Diffie—Hellman密钥交换(附完整源码)
查看>>
Objective-C实现Dijkstra最小路径算法(附完整源码)
查看>>