在application.properties中
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG,stdout
log4j.logger.httpclient.wire=DEBUG,stdout
management.endpoints.web.exposure.include=*
management.endpoint.beans.cache.time-to-live=10s
server.tomcat.accesslog.enabled = true
log4j.logger.org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod=DEBUG,stdout
logging.level.org.springframework.web=DEBUG,stdout
在这里
CommonsRequestLoggingFilter
记录其他请求,但不记录400。为什么?我该如何普遍处理?我对Spring Boot相当陌生,还无法实现restcontrolleradvice
控制器:
@CrossOrigin("*")
@RestController
public class DataController {
@RequestMapping(value = "/abc/track/{type}", method = RequestMethod.GET)
public void DummFunc(
@RequestParam(value="subs", required = false) String sub,
, HttpServletResponse response) {}
// @ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Throwable.class)
public void handle(HttpMessageNotReadableException e) {
System.out.println("EXCEPTION HAPPENED");
System.out.println(e);
}
}
答案 0 :(得分:0)
您可以在控制器中添加以下代码-
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public void handle(HttpMessageNotReadableException e) {
logger.warn("Returning HTTP 400 Bad Request", e);
}
如果您在@ControllerAdvice
级别添加class
,将可以全局访问。
不要忘记将类保留在可以由Spring boot扫描的包中
答案 1 :(得分:0)
您可以轻松实现ControllerAdvice
并处理异常,这里是示例代码:
@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<ExceptionResponse> handleAllExceptions(Exception ex, WebRequest request) {
ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(),
request.getDescription(false));
// doSomthing
return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
这是我的ExceptionResponse类:
public class ExceptionResponse {
private Date timestamp;
private String message;
private String details;
public ExceptionResponse(Date timestamp, String message, String details) {
super();
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
public Date getTimestamp() {
return timestamp;
}
public String getMessage() {
return message;
}
public String getDetails() {
return details;
}
}