博客
关于我
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实现Fedwick树算法(附完整源码)
查看>>
Objective-C实现fenwick tree芬威克树算法(附完整源码)
查看>>
Objective-C实现FenwickTree芬威克树算法(附完整源码)
查看>>
Objective-C实现fermat little theorem费马小定理算法(附完整源码)
查看>>
Objective-C实现FermatPrimalityTest费马素数测试算法(附完整源码)
查看>>
Objective-C实现fft2函数功能(附完整源码)
查看>>
Objective-C实现FFT快速傅立叶变换算法(附完整源码)
查看>>
Objective-C实现FFT算法(附完整源码)
查看>>
Objective-C实现fibonacci search斐波那契查找算法(附完整源码)
查看>>
Objective-C实现fibonacci斐波那契算法(附完整源码)
查看>>
Objective-C实现fibonacci斐波那契算法(附完整源码)
查看>>
Objective-C实现FIFO(附完整源码)
查看>>
Objective-C实现FigurateNumber垛积数算法(附完整源码)
查看>>
Objective-C实现finding bridges寻找桥梁算法(附完整源码)
查看>>
Objective-C实现first come first served先到先得算法(附完整源码)
查看>>
Objective-C实现FIR滤波器(附完整源码)
查看>>
Objective-C实现fischer yates shuffle洗牌算法(附完整源码)
查看>>
Objective-C实现FisherYates Shuffle洗牌算法(附完整源码)
查看>>
Objective-C实现fisherYates洗牌算法(附完整源码)
查看>>
Objective-C实现FloodFill洪水填充函数算法(附完整源码)
查看>>