我有一个带有
的帖子public Test postTest(@RequestBody Test test) {
}
public class Test {
@JsonProperty("EMAIL_ADDRESS")
@NotNull(message = "EMAIL_ADDRESS_NOT_NULL")
@Size(min = 1, message = "EMAIL_ADDRESS_NOT_EMPTY")
@Email(flags = Flag.CASE_INSENSITIVE, message = "EMAIL_INVALID")
private String emailAddress;
public ForgetPassword(
@NotNull(message = "EMAIL_ADDRESS_NOT_NULL") @Size(min = 1,
message = "EMAIL_ADDRESS_NOT_EMPTY") @Email(flags =
Flag.CASE_INSENSITIVE,
message = "EMAIL_INVALID") String emailAddress) {
super();
this.emailAddress = emailAddress;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
我缺少默认的构造函数,并且在尝试发布时,它始终返回错误的请求。如果我添加默认构造函数,则可以使用。它甚至不会抛出堆栈跟踪。我正在使用自定义模板来发送回响应。我重写了BadRequestException以发送回自定义消息。
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
}
是否有任何我应该重写的方法来捕获此类异常。我想知道为什么出问题了,并且能够看到堆栈痕迹。
答案 0 :(得分:1)
您可以使用@ControllerAdvice
定义全局异常处理程序。您可以使用@ExcecptionHandler
在此处放置尽可能多的处理程序。您可以记录errorTrace进行调试。
package com.startwithjava.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handlerGenericError(Exception ex){
ex.printStackTrace();
return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(BadRequestException.class)
public ResponseEntity<Object> handlerBadRequest(BadRequestException ex){
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
答案 1 :(得分:1)
您可以声明一个如下所示的类来处理异常。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
public class GlobalExceptionHandler {
private static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(Exception.class)
@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR, reason="Error processing the request, please check the logs")
public void handleException(Exception e) {
LOGGER.error("Exception occurred", e);
}
}