我正在尝试为我的控制器在Spring- Boot中编写错误处理程序,以捕获大多数可能的错误(Spring,sql等)。到目前为止,我可以通过Nulls获得JSON响应,但是我无法将任何数据放入其中。当我尝试收到错误消息时,我只会收到空白页。
import java.io.IOException; import java.sql.SQLException; import javax.servlet.http.HttpServletRequest; import org.springframework.boot.autoconfigure.web.ErrorController; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException; @RestController public class BasicErrorController implements ErrorController { private static final String ERROR_PATH = "/error"; @RequestMapping(value=ERROR_PATH) @ExceptionHandler(value = {NoSuchRequestHandlingMethodException.class, SQLException.class, IOException.class, RuntimeException.class, Exception.class}) public ErrorBody defaultErrorHandler(HttpServletRequest request, Exception e) { ErrorBody eBody = new ErrorBody(); eBody.setMessage(e.getCause().getMessage()); return eBody; } } import lombok.Getter; import lombok.Setter; @Getter @Setter public class ErrorBody { private String dateTime; private String exception; private String url; private String message; }
哟可以做这样的事情:
@ControllerAdvice public class ControllerExceptionTranslator { @ExceptionHandler(EntityNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) @ResponseBody SimpleErrorMessage handleException(EntityNotFoundException exception){ log.debug("Entity Not Found Exception {}",exception.getMessage()); log.trace(exception.getMessage(),exception); return new SimpleErrorMessage("Entity not found","This resource was not found"); } @ExceptionHandler({UsernameNotFoundException.class}) @ResponseStatus(HttpStatus.UNAUTHORIZED) @ResponseBody SimpleErrorMessage handleException(UsernameNotFoundException exception){ log.debug("Username not found {}",exception.getLocalizedMessage()); log.trace(exception.getMessage(),exception); return new SimpleErrorMessage("Unaouthorized"," "); } }