1. 程式人生 > >spring 的全域性異常處理

spring 的全域性異常處理

import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.config.ResourceNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 全域性異常處理器
 *
 */
@ControllerAdvice
@ResponseBody public class GlobalExceptionHandler { private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * @param e * @return */ @ExceptionHandler({ HttpMessageNotReadableException.class }) @ResponseStatus(value = HttpStatus.OK) public Map handleHttpException(HttpMessageNotReadableException e) { String msg = e.getMessage(); logger.info("HttpMessageNotReadableException : {}", msg); return ResultBuilder.failResult(msg);//直接返回map結果 } /** * ResourceNotFoundException處理 * @param e * @return */ @ExceptionHandler(value = ResourceNotFoundException.class) @ResponseStatus(value = HttpStatus.OK) public Map handleResourceNotFoundException(ResourceNotFoundException e) { String msg = e.getMessage(); logger.info("ResourceNotFoundException : {}", msg); if (StringUtils.isBlank(msg)) { msg = "資源不存在"; } return ResultBuilder.failResult(msg);//直接返回map結果 } /** * 其他異常處理 * @param e * @return */ @ExceptionHandler(value = Exception.class) @ResponseStatus(value = HttpStatus.OK) public Map handleException(Exception e) { // 記錄錯誤資訊 logger.error(e.getMessage()); String msg = e.getMessage(); if (msg == null || msg.equals("")) { msg = "伺服器出錯,請聯絡管理員"; } return ResultBuilder.failResult(msg);//直接返回map結果 } }