一、前言
有时候不可避免服务器报错的情况,如果不配置异常处理机制,就会默认返回tomcat或者nginx的5XX页面,对普通用户来说,不太友好,用户也不懂什么情况。这时候需要我们程序员设计返回一个友好简单的格式给前端。
二、处理方法
处理办法如下:通过使用@ControllerAdvice
来进行统一异常处理,@ExceptionHandler(value = RuntimeException.class)
来指定捕获的Exception各个类型异常 ,这个异常的处理,是全局的,所有类似的异常,都会跑到这个地方处理。步骤二、定义全局异常处理,@ControllerAdvice
表示定义全局控制器异常处理,@ExceptionHandler
表示针对性异常处理,可对每种异常针对性处理,@ResponseStatus()
表示返回的状态码。
2.1、代码
package com.zzuli.common.exception;
import com.zzuli.common.api.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.nio.file.AccessDeniedException;
/**
* 全局异常处理
*/
@Slf4j
@RestControllerAdvice
class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(value = AccessDeniedException.class)
public CommonResult<String> handler(AccessDeniedException e) {
log.info("security权限不足:----------------{}", e.getMessage());
return CommonResult.failed("权限不足");
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public CommonResult<String> handler(MethodArgumentNotValidException e) {
log.info("实体校验异常:----------------{}", e.getMessage());
BindingResult bindingResult = e.getBindingResult();
ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
return CommonResult.failed(objectError.getDefaultMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = IllegalArgumentException.class)
public CommonResult<String> handler(IllegalArgumentException e) {
log.error("Assert异常:----------------{}", e.getMessage());
return CommonResult.failed(e.getMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = RuntimeException.class)
public CommonResult<String> handler(RuntimeException e) {
log.error("运行时异常:----------------{}", e);
return CommonResult.failed(e.getMessage());
}
}
其中需要的结果集在以下文章https://blog.csdn.net/niulinbiao/article/details/120095584