课程名称:Spring Cloud / Alibaba 微服务架构实战
课程章节:第3章-设计电商工程,把握全局视角
课程讲师:张勤一
课程内容:
1. 构建统一响应格式
package com.imooc.ecommerce.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CommonResponse<T> implements Serializable {
private Integer code;
private String message;
private T Data;
public CommonResponse(Integer code, String message) {
this.code = code;
this.message = message;
}
}
package com.imooc.ecommerce.annotation;
import java.lang.annotation.*;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface IgnoreResponseAdvice {
}
package com.imooc.ecommerce.advice;
import com.imooc.ecommerce.annotation.IgnoreResponseAdvice;
import com.imooc.ecommerce.vo.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@RestControllerAdvice(value = "com.imooc.ecommerce")
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {
@Override
@SuppressWarnings("all")
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
if (methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class)){
return false;
}
if (methodParameter.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class)){
return false;
}
return true;
}
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter,
MediaType mediaType,
Class<? extends HttpMessageConverter<?>> aClass,
ServerHttpRequest serverHttpRequest,
ServerHttpResponse serverHttpResponse) {
CommonResponse<Object> response = new CommonResponse<>(0, "");
if (null == o){
return response;
}else if (o instanceof CommonResponse){
return o;
}else {
response.setData(o);
}
return response;
}
}
2. 构建统一异常格式
package com.imooc.ecommerce.advice;
import com.imooc.ecommerce.vo.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {
@ExceptionHandler(value = Exception.class)
public CommonResponse<String> handlerCommerceException(HttpServletRequest request, Exception e){
CommonResponse<String> response = new CommonResponse<>(-1, "business error");
response.setData(e.getMessage());
log.error("================>commerce service has error: [{}]", e.getMessage(), e);
return response;
}
}
课程截图:
打开App,阅读手记