随笔 - 43  文章 - 0  评论 - 1  阅读 - 80506

SpringBoot使用 @ExceptionHandler 做 自定义异常处理

目的是,更友好的页面访问。

自定义的异常捕获类

复制代码
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class CustomExtHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomExtHandler.class);

    @ExceptionHandler(value = {Exception.class})
    Object handleException(Exception e, HttpServletRequest request){
        LOGGER.error("url: {}, msg: {}", request.getRequestURL(), e.getMessage());
        Map<String, Object> map = new HashMap<>();
        map.put("code", 100);
        map.put("msg", e.getMessage());
        map.put("url", request.getRequestURL());

        return map;
    }

}
复制代码

 

 这里的  @ExceptionHandler(value = {Exception.class}) , 表示 捕获 全部异常。

注意:

  • 添加注解@ControllerAdvice 。

  • 如果是返回json数据 则用 @RestControllerAdvice,就可以不加 @ResponseBody。

 

通过 controller 模拟异常。

@RequestMapping(value = "/api/v1/test_ext")
public Object index(){
    int i= 1/0;
    return new User(29,"abc","139",new Date());
}

 

 

测试,访问 http://localhost:8080/api/v1/test_ext 

{
"msg": "/ by zero",
"code": 100,
"url": "http://localhost:8080/api/v1/test_ext"
}

 

返回自定义的页面

设置捕获的处理方法,在CustomExtHandler,添加方法。

 

@ExceptionHandler(value = {MyException.class})
Object handleMyException(MyException e, HttpServletRequest request){
    //进行页面跳转
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("error.html");
    modelAndView.addObject("msg", e.getMsg());
    return modelAndView;
}

 

 这里做了 自定义的 页面跳转。 不适合 前后端分离的开发模式。

 

还是返回 json 更好。

return new MyException("601", "自定义的错误页面,给到前台。");

 

 

 自定义返回的Json。

复制代码
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class MyException extends RuntimeException {
    private String code;
    private String msg;
}
复制代码

 

posted on   wuyicode  阅读(7738)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示