网站开发服务费合同范本,锡林浩特建设局网站,卖猕猴桃网站建设宣传策划书,吐鲁番做网站这篇文章将说明在Spring中可以为RESTful Web服务实现异常处理的方式#xff0c;这种方式使得异常处理的关注点与应用程序逻辑分离。 利用ControllerAdvice批注#xff0c;我们能够为所有控制器创建一个全局帮助器类。 通过添加用ExceptionHandler和ResponseStatus注释的方法… 这篇文章将说明在Spring中可以为RESTful Web服务实现异常处理的方式这种方式使得异常处理的关注点与应用程序逻辑分离。 利用ControllerAdvice批注我们能够为所有控制器创建一个全局帮助器类。 通过添加用ExceptionHandler和ResponseStatus注释的方法我们可以指定将哪种类型的异常映射到哪种HTTP响应状态。 例如我们的自定义NotFoundException可以映射到404 Not Found的HTTP响应或者通过捕获java.lang.Exception 所有未在其他地方捕获的异常都将导致HTTP状态500 Internal Server Error 或者IllegalArgumentException可能导致400 Bad请求 或者……好吧我确定您已经有了大致的想法。 如果需要您还可以通过将ResponseBody添加到组合中将更多详细信息发送回客户端。 以下是一个非常有限的示例可以帮助您入门。 GeneralRestExceptionHandler package it.jdev.examples.spring.rest.exceptions;import java.lang.invoke.MethodHandles;
import org.slf4j.*;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;ControllerAdvice
Order(Ordered.LOWEST_PRECEDENCE)
public class GeneralRestExceptionHandler {private static final Logger LOGGER LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());ResponseStatus(HttpStatus.NOT_FOUND)ExceptionHandler(CustomNotFoundException.class)public void handleNotFoundException(final Exception exception) {logException(exception);}ResponseStatus(HttpStatus.FORBIDDEN)ExceptionHandler(CustomForbiddenException.class)public void handleForbiddenException(final Exception exception) {logException(exception);}ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)ExceptionHandler({ CustomException.class, Exception.class })public void handleGeneralException(final Exception exception) {logException(exception);}ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)ExceptionHandler(Exception.class)public void handleGeneralException(final Exception exception) {logException(exception);}ResponseStatus(HttpStatus.BAD_REQUEST)ExceptionHandler({ CustomBadRequestException.class, IllegalArgumentException.class })ResponseBodypublic String handleBadRequestException(final Exception exception) {logException(exception);return exception.getMessage();}// Add more exception handling as needed…// …private void logException(final Exception exception) {// ...}}翻译自: https://www.javacodegeeks.com/2015/06/restful-error-handling-with-spring.html