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


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

被折叠的 条评论
为什么被折叠?



