假设您有一个自定义的Exception类NotFoundException
及其实现,如下所示:
public class NotFoundException extends Exception {
private int errorCode;
private String errorMessage;
public NotFoundException(Throwable throwable) {
super(throwable);
}
public NotFoundException(String msg, Throwable throwable) {
super(msg, throwable);
}
public NotFoundException(String msg) {
super(msg);
}
public NotFoundException(String message, int errorCode) {
super();
this.errorCode = errorCode;
this.errorMessage = message;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getErrorMessage() {
return errorMessage;
}
@Override
public String toString() {
return this.errorCode + " : " + this.getErrorMessage();
}
}
现在,您想从控制器抛出一些异常。如果抛出异常,则必须从标准错误处理程序类中捕获该异常,例如在spring说,它们提供了@ControllerAdvice
注释以应用于制作标准错误处理程序类。当将它应用于类时,该spring组件(我是说您注释的类)可以捕获从控制器抛出的任何异常。但是我们需要使用适当的方法来映射异常类。因此,我们为您的异常NotFoundException
处理程序定义了一种方法,如下所示。
@ControllerAdvice
public class RestErrorHandler {
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public Object processValidationError(NotFoundException ex) {
String result = ex.getErrorMessage();
System.out.println("###########"+result);
return ex;
}
}
您想将 发送 ,因此在这里我们使用@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
。由于您使用了Spring- boot,因此您无需制作json字符串,只需简单的注释@ResponseBody
即可自动完成。