javascript
Spring RESTful错误处理
這篇文章將說明在Spring中可以為RESTful Web服務(wù)實現(xiàn)異常處理的方式,這種方式使得異常處理的關(guān)注點與應(yīng)用程序邏輯分離。
利用@ControllerAdvice批注,我們能夠為所有控制器創(chuàng)建一個全局幫助器類。 通過添加用@ExceptionHandler和@ResponseStatus注釋的方法,我們可以指定將哪種類型的異常映射到哪種HTTP響應(yīng)狀態(tài)。 例如,我們的自定義NotFoundException可以映射到404 Not Found的HTTP響應(yīng),或者通過捕獲java.lang.Exception ,所有未在其他地方捕獲的異常都將導(dǎo)致HTTP狀態(tài)500 Internal Server Error ,或者IllegalArgumentException可能導(dǎo)致400 Bad請求 ,或者……好吧,我確定您已經(jīng)有了大致的想法。
如果需要,您還可以通過將@ResponseBody添加到組合中,將更多詳細(xì)信息發(fā)送回客戶端。
以下是一個非常有限的示例,可以幫助您入門。
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
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的Spring RESTful错误处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 399送平板电脑(399买块手表送手机或
- 下一篇: 使用Java将数据流式传输到HPCC