SpringBoot全局異常處理之解決404/500錯(cuò)誤
前言
SpringBoot要全局處理 Spring Boot 應(yīng)用程序中的 HTTP 404 和 500 錯(cuò)誤,您可以自定義一個(gè)異常處理器類(lèi),并使用 @ControllerAdvice
和 @ExceptionHandler
注釋來(lái)攔截和處理這些異常。
解決方案
下面是一種可能的實(shí)現(xiàn)方式,它捕獲HTTP GET請(qǐng)求中PathVariable
參數(shù)類(lèi)型不匹配、參數(shù)格式錯(cuò)誤以及其他所有未處理的異常,并返回一個(gè)包含錯(cuò)誤代碼和錯(cuò)誤消息的 Map 對(duì)象:
@ControllerAdvice public class GlobalExceptionHandler { // 捕獲 PathVariable 參數(shù)類(lèi)型不匹配或格式錯(cuò)誤的異常,并返回錯(cuò)誤信息 @ExceptionHandler(MethodArgumentTypeMismatchException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public Map<String, Object> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex) { return createErrorResponse(HttpStatus.BAD_REQUEST.value(), "請(qǐng)求參數(shù)有誤: " + ex.getMessage()); } // 捕獲其他未處理的異常,并返回錯(cuò)誤信息 @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody public Map<String, Object> handleUncaughtException(Exception ex) { return createErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系統(tǒng)內(nèi)部錯(cuò)誤: " + ex.getMessage()); } // 創(chuàng)建包含錯(cuò)誤碼和錯(cuò)誤消息的 Map 對(duì)象 private Map<String, Object> createErrorResponse(int code, String message) { Map<String, Object> errorResponse = new HashMap<>(); errorResponse.put("code", code); errorResponse.put("message", message); return errorResponse; } }
說(shuō)明:
在此示例中:
- 使用
@ControllerAdvice
和@ExceptionHandler
注釋標(biāo)識(shí)此類(lèi)為全局異常處理程序,并捕獲了MethodArgumentTypeMismatchException
和任何其他未處理的異常。 - 使用
@ResponseStatus(HttpStatus.BAD_REQUEST)
和@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
來(lái)指定異常的 HTTP 響應(yīng)狀態(tài)碼。 - 使用
@ResponseBody
注釋來(lái)告訴 Spring Boot 應(yīng)用程序,我們不想呈現(xiàn)采用模板引擎進(jìn)行渲染的視圖,而是返回具體的響應(yīng)正文對(duì)象。createErrorResponse()
方法創(chuàng)建并返回包含錯(cuò)誤代碼和錯(cuò)誤消息的 Map 對(duì)象。
通用的全局異常處理
@ControllerAdvice public class GlobalExceptionHandler { /** * 處理 HTTP 404 錯(cuò)誤 */ @ExceptionHandler(NoHandlerFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) @ResponseBody public ApiError handleNotFound(HttpServletRequest req, Exception ex) { return new ApiError(HttpStatus.NOT_FOUND.value(), "無(wú)該資源: " + req.getRequestURI()); } /** * 處理 HTTP 500 錯(cuò)誤 */ @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody public ApiError handleInternalServerError(HttpServletRequest req, Exception ex) { return new ApiError(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服務(wù)器內(nèi)部錯(cuò)誤: " + ex.getMessage()); } /** * 處理用戶登錄異常 */ @ExceptionHandler(UserLoginException.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) @ResponseBody public ApiError handleUserLoginException(HttpServletRequest req, UserLoginException ex) { return new ApiError(HttpStatus.UNAUTHORIZED.value(), "用戶登錄失敗: " + ex.getMessage()); } /** * 處理其他所有未處理的異常 */ @ExceptionHandler(Throwable.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody public ApiError handleOtherExceptions(HttpServletRequest req, Throwable ex) { return new ApiError(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系統(tǒng)內(nèi)部錯(cuò)誤: " + ex.getMessage()); } }
觸發(fā)異常
我們?cè)诳刂破髦心M一個(gè)用戶登錄失敗的場(chǎng)景,并將 UserLoginException 拋出:
@RestController public class UserController { @Autowired private UserService userService; @PostMapping("/login") public String login(@RequestBody LoginForm form) { // 驗(yàn)證用戶名和密碼 if (!userService.validate(form.getUsername(), form.getPassword())) { // 用戶不存在或密碼錯(cuò)誤,拋出 UserLoginException 異常 throw new UserLoginException("用戶名或密碼不正確"); } // 登錄成功,返回 token 或用戶信息 // ...... } }
總結(jié)
到此這篇關(guān)于SpringBoot全局異常處理之解決404/500錯(cuò)誤的文章就介紹到這了,更多相關(guān)SpringBoot解決404 500錯(cuò)誤內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java8中List轉(zhuǎn)Map(Collectors.toMap) 的技巧分享
在最近的工作開(kāi)發(fā)之中,慢慢習(xí)慣了很多Java8中的Stream的用法,很方便而且也可以并行的去執(zhí)行這個(gè)流,這篇文章主要給大家介紹了關(guān)于Java8中List轉(zhuǎn)Map(Collectors.toMap) 的相關(guān)資料,需要的朋友可以參考下2021-07-07SpringCloud消息總線Bus配置中心實(shí)現(xiàn)過(guò)程解析
這篇文章主要介紹了SpringCloud消息總線Bus配置中心實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03詳解WebSocket+spring示例demo(已使用sockJs庫(kù))
本篇文章主要介紹了WebSocket spring示例demo(已使用sockJs庫(kù)),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-01-01使用SpringBoot Actuator監(jiān)控應(yīng)用示例
Actuator是Spring Boot提供的對(duì)應(yīng)用系統(tǒng)的自省和監(jiān)控的集成功能,可以對(duì)應(yīng)用系統(tǒng)進(jìn)行配置查看、相關(guān)功能統(tǒng)計(jì)等。這篇文章主要介紹了使用SpringBoot Actuator監(jiān)控應(yīng),有興趣的可以了解一下2018-05-05Redisson分布式閉鎖RCountDownLatch的使用詳細(xì)講解
分布式鎖和我們java基礎(chǔ)中學(xué)習(xí)到的synchronized略有不同,synchronized中我們的鎖是個(gè)對(duì)象,當(dāng)前系統(tǒng)部署在不同的服務(wù)實(shí)例上,單純使用synchronized或者lock已經(jīng)無(wú)法滿足對(duì)庫(kù)存一致性的判斷。本次主要講解基于rediss實(shí)現(xiàn)的分布式鎖2023-02-02springBoot使用openfeign來(lái)遠(yuǎn)程調(diào)用的實(shí)現(xiàn)
這篇文章主要介紹了springBoot使用openfeign來(lái)遠(yuǎn)程調(diào)用的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03