统一异常处理
spring统一异常处理类
package com.strap.mydemo.components;
import com.strap.mydemo.dto.BaseResultDTO;
import com.strap.mydemo.enums.BaseResultType;
import com.strap.mydemo.exceptions.BaseResultException;
import com.strap.mydemo.result.IResultCode;
import lombok.extern.log4j.Log4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* <p>统一异常拦截处理</p>
*
* @author strap
*/
@RestControllerAdvice
@Log4j
public class BaseResultExceptionHandler {
public BaseResultExceptionHandler() {
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.OK) // 定义返回的状态码
public Object handlerException(Exception ex) {
BaseResultDTO<Object> res = new BaseResultDTO<>();
if (ex instanceof BaseResultException) {
BaseResultException exception = (BaseResultException) ex;
IResultCode iResultCode = exception.getIResultCode();
res.setCode(iResultCode.getCode()).setMsg(exception.getMessage());
} else {
res.setCode(BaseResultType.FAILED.getCode()).setMsg(BaseResultType.FAILED.getMessage());
}
log.error("error:", ex);
return res;
}
}