步骤:
1.在微服务项目中创建一个公共模块
2.在公共模块中编写全局异常处理的代码
定义错误信息接口
package com.springcloud.common.Exception;
public interface ErrorCode {
int getcode();
String getdesc();
}
编写错误信息接口实现类
package com.springcloud.common.Exception;
public enum ErrorCodeimpl implements ErrorCode{
UNAUTHORIZED(401, "未认证"),
/**
* 未知错误
*/
UNKNOWN(999999, "未知错误");
private final Integer code;
private final String desc;
ErrorCodeimpl(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public int getcode() {
return 0;
}
@Override
public String getdesc() {
return null;
}
}
自定义异常类
package com.springcloud.common.Exception;
public class BusinessException extends RuntimeException {
private ErrorCode errorCode;
public BusinessException(ErrorCode errorCode)
{
super(errorCode.getdesc());
this.errorCode=errorCode;
}
public ErrorCode getErrorCode() {
return errorCode;
}
}
定义全局异常处理器
package com.springcloud.common.Exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
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;
import java.util.Objects;
@ControllerAdvice
public class GlobalExceptionHandler {
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorRestResult handle(MethodArgumentNotValidException exception)
{
//返回错误字段
String field = Objects.requireNonNull(exception.getBindingResult().getFieldError()).getField();
//返回错误信息
String message = exception.getBindingResult().getFieldError().getDefaultMessage();
return new ErrorRestResult(HttpStatus.BAD_REQUEST.toString(),field+message);
}
@ResponseBody
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorRestResult handle(Exception exception)
{
if(exception instanceof BusinessException)
{
BusinessException ex = (BusinessException) exception;
ErrorCode errorCode = ex.getErrorCode();
int getcode = errorCode.getcode();
String getdesc = errorCode.getdesc();
return new ErrorRestResult(String.valueOf(getcode),getdesc);
}
return new ErrorRestResult(String.valueOf(ErrorCodeimpl.UNKNOWN.getcode()),exception.getMessage()!=null? exception.getMessage():ErrorCodeimpl.UNKNOWN.getdesc());
}
}
3.在所需要引入公共模块的某个服务内添加公共模块的依赖
<dependency>
<groupId>org.example</groupId>
<artifactId>commom-service</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
4.在引入模块服务的启动类上添加注解(非常关键)
@Import(GlobalExceptionHandler.class)