博客
关于我
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实现CircularQueue循环队列算法(附完整源码)
查看>>
Objective-C实现clearBit清除位算法(附完整源码)
查看>>
Objective-C实现climbStairs爬楼梯问题算法(附完整源码)
查看>>
Objective-C实现cocktail shaker sort鸡尾酒排序算法(附完整源码)
查看>>
Objective-C实现cocktailShakerSort鸡尾酒排序算法(附完整源码)
查看>>
Objective-C实现CoinChange硬币兑换问题算法(附完整源码)
查看>>
Objective-C实现collatz sequence考拉兹序列算法(附完整源码)
查看>>
Objective-C实现Collatz 序列算法(附完整源码)
查看>>
Objective-C实现comb sort梳状排序算法(附完整源码)
查看>>
Objective-C实现combinationSum组合和算法(附完整源码)
查看>>
Objective-C实现combinations排列组合算法(附完整源码)
查看>>
Objective-C实现combine With Repetitions结合重复算法(附完整源码)
查看>>
Objective-C实现combine Without Repetitions不重复地结合算法(附完整源码)
查看>>
Objective-C实现conjugate gradient共轭梯度算法(附完整源码)
查看>>
Objective-C实现connected components连通分量算法(附完整源码)
查看>>
Objective-C实现Connected Components连通分量算法(附完整源码)
查看>>
Objective-C实现Convex hull凸包问题算法(附完整源码)
查看>>
Objective-C实现convolution neural network卷积神经网络算法(附完整源码)
查看>>
Objective-C实现convolve卷积算法(附完整源码)
查看>>
Objective-C实现coulombs law库仑定律算法(附完整源码)
查看>>