@ControllerAdvice配置讲解:
package cn.org.spring.wechar.exception;
import cn.org.spring.wechar.bean.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* @author: 谢辉
* @date: 2021/5/20
* @email: xieh_mail@163.com
* @description: 集中处理所有controller异常
* @modifiedBy:
* @version: 1.0
*/
@Slf4j
@ControllerAdvice(basePackages = "cn.org.spring.wechar")
public class ExceptionControllerAdvice {
/**
* 响应json数据
* @param throwable
* @return
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Result handleException(Exception throwable) {
log.error("错误异常{}", throwable);
return Result.fail("发生未知错误,稍后在试~");
}
/**
* 跳转页面
* @param throwable
* @return
*/
@ExceptionHandler(value = Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handle(Exception throwable) {
log.error("错误异常{}", throwable);
return "error/500";
}
}
错误页面配置:
package cn.org.spring.wechar.config;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
/**
* @author: 谢辉
* @date: 2021/5/20
* @email: xieh_mail@163.com
* @description: 错误页面配置
* @modifiedBy:
* @version: 1.0
*/
@Component
public class ErrorPageConfig implements ErrorPageRegistrar {
@Override
public void registerErrorPages(ErrorPageRegistry registry) {
//1、按错误的类型显示错误的网页
//错误类型为404,找不到网页的,默认显示404.html网页
ErrorPage e404 = new ErrorPage(HttpStatus.NOT_FOUND, "/common/error/404");
//错误类型为500,表示服务器响应错误,默认显示500.html网页
ErrorPage e500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/common/error/500");
registry.addErrorPages(e404, e500);
}
}
package cn.org.spring.wechar.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author: 谢辉
* @date: 2021/5/20
* @email: xieh_mail@163.com
* @description:
* @modifiedBy:
* @version: 1.0
*/
@Controller
@RequestMapping("/common")
public class CommonController {
@RequestMapping("/error/404")
public String error404() {
return "error/404";
}
@RequestMapping("/error/500")
public String error500() {
return "error/500";
}
}
注意:
@ControllerAdvice可以捕捉服务器内部错误例如5xx之类的错误或者自定义的异常,可以选择响应json数据或者跳转页面,但是例如404之类的错误是捕捉不到的。
ErrorPageRegistrar接口配置错误页面也可以响应json数据,或者跳转页面,ErrorPageRegistrar可以捕捉404之类和500之类的错误范围更广,但是无法捕获自定义异常。
如果@ControllerAdvice和ErrorPageRegistrar同时捕捉500错误,@ControllerAdvice优先级比ErrorPageRegistrar高。
总结:
@ControllerAdvice可以捕捉自定义异常和服务器500之类的异常,但是404之类的是捕获不到的
ErrorPageRegistrar可以捕获500服务器错误或者404之类的错误,但是无法捕获自定义异常
相同配置时@ControllerAdvice优先级比ErrorPageRegistrar高