Custom Exception
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 1L;
private int status = 200;
private String code = "";
private String trace = "";
public BusinessException() {
super();
}
public BusinessException(int status, String code, String message) {
this(status, code, message, "");
}
public BusinessException(int status, String code, String message, String trace) {
super(message);
this.status = status;
this.code = code;
this.trace = trace;
}
public int getStatus() {
return status;
}
public String getCode() {
return code;
}
public String getTrace() {
return trace;
}
}
Exception handling of Handler
@Component
@Order(-2)
public class GlobalDefaultExceptionHandler extends AbstractErrorWebExceptionHandler {
public GlobalDefaultExceptionHandler(ErrorAttributes g, ApplicationContext applicationContext,
ServerCodecConfigurer serverCodecConfigurer) {
super(g, new ResourceProperties(), applicationContext);
super.setMessageWriters(serverCodecConfigurer.getWriters());
super.setMessageReaders(serverCodecConfigurer.getReaders());
}
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
private Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
var errorPropertiesMap = getErrorAttributes(request, false);
var status = (int) errorPropertiesMap.get("status");
var exception = this.getError(request);
var code = "";
var message = "";
if (exception instanceof BusinessException) {
var businessException = (BusinessException) exception;
status = businessException.getStatus();
code = businessException.getCode();
message = exception.getMessage();
} else {
code = String.valueOf(status);
if (status == 400) {
message = "参数错误";
} else if (status == 401) {
message = "无权访问";
} else if (status == 404) {
message = "未找到";
} else if (status == 500) {
message = "服务内部错误";
}
}
var errorMap = new HashMap<String, Object>();
errorMap.put("code", code);
errorMap.put("message", message);
return ServerResponse.status(HttpStatus.valueOf(status)).contentType(MediaType.APPLICATION_JSON_UTF8)
.body(BodyInserters.fromObject(errorMap));
}
}
Feign Exception Handling
@Component
public class ExceptionErrorDecoder implements ErrorDecoder {
@Autowired
private ObjectMapper objectMapper;
@Override
public Exception decode(String methodKey, Response response) {
BusinessException businessException = null;
try {
Map<String, String> content = objectMapper.readValue(response.body().asInputStream(),
new TypeReference<Map<String, String>>() {
});
businessException = new BusinessException(response.status(), content.getOrDefault("code", ""),
content.getOrDefault("message", ""), content.getOrDefault("trace", ""));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return businessException;
}
}
Reproduced in: https: //www.jianshu.com/p/58aab43a5306