08-自定义错误处理

本文介绍如何在Spring MVC中自定义统一异常处理,通过创建CommonException类使用@ControllerAdvice注解,并定义错误页面如404、500、501等。同时演示了在UserController中增加异常处理测试接口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.在resources/public/error/ 下定义404html\500.html\501.html

2.创建CommonException类并用注解@ControllerAdvice自定义统一异常处理

package com.study.model.commonError;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

public class CommonException {
    private static final Logger log= LoggerFactory.getLogger(CommonException.class);
    @ExceptionHandler({RuntimeException.class})
    @ResponseStatus(HttpStatus.OK)
    public ModelAndView processException(RuntimeException exception){
        log.info("自定义异常处理-RuntimeException");
        ModelAndView m=new ModelAndView();
        m.addObject("roncooException",exception.getMessage());
        m.setViewName("/error/501.html");
        return m;
    }
    @ExceptionHandler({Exception.class})
    @ResponseStatus(HttpStatus.OK)
    public ModelAndView processException(Exception exception){
        log.info("自定义异常处理-Exception");
        ModelAndView m=new ModelAndView();
        m.addObject("roncooException",exception.getMessage());
        m.setViewName("/error/500.html");
        return m;
    }

}

     在设置错误页面时,虽然我的错误页面是在public/error下面,但是路径上不能加public,不然就跑去404页面而不是匹配的页面

3.在UserController增加异常处理测试接口

@ApiOperation(value = "测试异常",notes = "测试异常处理")
@RequestMapping(value = "/error",method = RequestMethod.GET)
public String error(){
    throw new RuntimeException("测试异常");
}
@ApiOperation(value = "测试异常",notes = "测试异常处理")
@RequestMapping(value = "/errora",method = RequestMethod.GET)
public String errora() throws Exception{
    throw new Exception();
}

                             在抛出exception异常时要先在方法上抛出异常,不然会报Exception没有被处理错误

4.运行,访问http://localhost:8080/user/error    http://localhost8080/user/errora  

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值