优化异常处理

This commit is contained in:
zhou-hao 2020-03-13 14:31:58 +08:00
parent a0f2957df0
commit 9d0c2d041c
2 changed files with 36 additions and 3 deletions

View File

@ -157,6 +157,9 @@ public class DeviceMessageController {
private static <R extends DeviceMessageReply, T> Function<R, T> mapReply(Function<R, T> function) {
return reply -> {
if (ErrorCode.REQUEST_HANDLING.name().equals(reply.getCode())) {
throw new DeviceOperationException(ErrorCode.REQUEST_HANDLING, reply.getMessage());
}
if (!reply.isSuccess()) {
throw new BusinessException(reply.getMessage(), reply.getCode());
}

View File

@ -2,10 +2,12 @@ package org.jetlinks.community.standalone.configuration;
import lombok.extern.slf4j.Slf4j;
import org.hswebframework.web.crud.web.ResponseMessage;
import org.jetlinks.core.enums.ErrorCode;
import org.jetlinks.core.exception.DeviceOperationException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@ -17,9 +19,37 @@ import reactor.core.publisher.Mono;
public class ErrorControllerAdvice {
@ExceptionHandler
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Mono<ResponseMessage<?>> handleException(DeviceOperationException e) {
return Mono.just(ResponseMessage.error(e.getCode().name().toLowerCase(), e.getMessage()));
public Mono<ResponseEntity<ResponseMessage<Object>>> handleException(DeviceOperationException e) {
//202
if (e.getCode() == ErrorCode.REQUEST_HANDLING) {
return Mono.just(ResponseEntity
.status(HttpStatus.ACCEPTED)
.body(ResponseMessage.error(202,
e.getCode().name().toLowerCase(),
e.getMessage())
.result("消息已发往设备,处理中...")));
}
if (e.getCode() == ErrorCode.FUNCTION_UNDEFINED
|| e.getCode() == ErrorCode.PARAMETER_UNDEFINED) {
//404
return Mono.just(ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(ResponseMessage.error(e.getCode().name().toLowerCase(), e.getMessage())));
}
if (e.getCode() == ErrorCode.PARAMETER_UNDEFINED) {
//400
return Mono.just(ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(ResponseMessage.error(e.getCode().name().toLowerCase(), e.getMessage())));
}
//500
return Mono.just(ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ResponseMessage.error(e.getCode().name().toLowerCase(), e.getMessage())));
}
}