package com.canrd.webmagic.common.exception; import com.canrd.webmagic.common.constant.ServerResult; import com.canrd.webmagic.common.constant.ServerResultCode; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import java.util.Optional; /** * 业务异常统一处理类 * * @date 2021/1/11 */ @ControllerAdvice @Order(5) public class BusinessExceptionHandlerAdvice { @ExceptionHandler(value = {BusinessException.class}) @ResponseStatus(value = HttpStatus.OK) public ResponseEntity<Object> handleException(BusinessException exception) throws Exception { return new ResponseEntity<Object>(handleBusinessException(exception), HttpStatus.OK); } private ServerResult handleBusinessException(BusinessException exception) { Integer code = Optional.ofNullable(exception.getErrorCode()).orElse(ServerResultCode.FAIL.getErrorCode()); String msg = Optional.ofNullable(exception.getMessage()).orElse(ServerResultCode.FAIL.getErrorDesc()); Object data = Optional.ofNullable(exception.getData()).orElse(null); return ServerResult.fail(data, code, msg); } }