@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY)
@Getter(AccessLevel.PUBLIC)
@Setter(AccessLevel.PROTECTED)
@NoArgsConstructor
@组件
公共类 ErrorJson {
public Integer status;
public String error;
@JsonIgnore
public String message;
public String timeStamp;
public String trace;
public ErrorJson(int status, Map<String, Object> errorAttributes) {
this.status = status;
this.error = (String) errorAttributes.get("error");
this.message = (String) errorAttributes.get("message");
this.timeStamp = errorAttributes.get("timestamp").toString();
this.trace = (String) errorAttributes.get("trace");
}
}
@日志
@PropertySource("classpath:application.properties")
@配置
@ComponentScan("com")
@RestController
公共类 CustomErrorController 实现 ErrorController {
private static final String PATH = "/error";
@Value("${custom-error-controller.debug}")
private boolean debug;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
@Autowired
private ErrorAttributes errorAttributes;
@RequestMapping(value = PATH)
ResponseEntity<ErrorJson> error(HttpServletRequest request, HttpServletResponse response){
return ResponseEntity.status(response.getStatus())
.body(
new ErrorJson(response.getStatus(), getErrorAttributes(request, debug)
)
);
}
@Override
public String getErrorPath(){
return PATH;
}
private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace);
}
}