1. 程式人生 > >Spring boot全局捕獲異常處理!

Spring boot全局捕獲異常處理!

resultmap () del 進行 指定 return spring ring com

package com.htli.util;

import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public
class GlobalExceptionHandler { /** * @ExceptionHandler 表示攔截異常 * @ControllerAdvice 是 controller 的一個輔助類,最常用的就是作為全局異常處理的切面類 * @ControllerAdvice 可以指定掃描範圍 * @ControllerAdvice 約定了幾種可行的返回值,如果是直接返回 model 類的話,需要使用 @ResponseBody 進行 json 轉換 * 返回 String,表示跳到某個 view * 返回 modelAndView * 返回 model + @ResponseBody
*/ /** * 返回json字符串的 還有返回modeAndView的 * @return */ @ExceptionHandler(RuntimeException.class) @ResponseBody public Map<String, Object> exceptionHandler(){ Map<String, Object> errorResultMap = new HashMap<String, Object>(); errorResultMap.put(
"errorCode", "500"); errorResultMap.put("errorMsg", "系統錯誤!"); return errorResultMap; } }

一個捕獲異常的工具類

Spring boot全局捕獲異常處理!