當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring RESTful错误处理
生活随笔
收集整理的這篇文章主要介紹了
Spring RESTful错误处理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這篇文章將說明在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
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Spring RESTful错误处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 399送平板电脑(399买块手表送手机或
- 下一篇: gradle idea java ssm