spring boot --> 全局異常處理

package com.jscz;java

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
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;
import org.springframework.web.servlet.NoHandlerFoundException;web

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.xml.bind.ValidationException;
import java.util.Set;spring

/**
 * 異常處理類
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionController {
    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionController.class);
 
 
    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public String handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        logger.error("handleMissingServletRequestParameterException缺乏請求參數", e);
        return "handleMissingServletRequestParameterException缺乏請求參數";
    }
    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public String handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        logger.error("handleHttpMessageNotReadableException參數解析失敗", e);
        return "handleHttpMessageNotReadableException參數解析失敗";
    }
 
    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error("handleMethodArgumentNotValidException參數驗證失敗", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        return "handleMethodArgumentNotValidException參數驗證失敗="+message;
    }
    
    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(IllegalArgumentException.class)
    public String IllegalArgumentException(MethodArgumentNotValidException e) {
        logger.error("IllegalArgumentException------>>>>>>>>>>>>", e);
        return "IllegalArgumentException------>>>>>>>>>>>>錯誤";
    }
 
    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public String handleBindException(BindException e) {
        logger.error("handleBindException參數綁定失敗", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        return "handleBindException參數綁定失敗="+message;
    }
 
 
    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ConstraintViolationException.class)
    public String handleServiceException(ConstraintViolationException e) {
        logger.error("handleServiceException參數驗證失敗", e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        ConstraintViolation<?> violation = violations.iterator().next();
        String message = violation.getMessage();
        return "handleServiceException參數驗證失敗" + message;
    }
 
    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public String handleValidationException(ValidationException e) {
        logger.error("handleValidationException參數驗證失敗", e);
        return "handleValidationException參數驗證失敗";
    }
 
    /**
     * 404 - Not Found
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public String noHandlerFoundException(NoHandlerFoundException e) {
        logger.error("noHandlerFoundException    Not Found", e);
        return "noHandlerFoundException    Not Found="+e;
    }
 
 
    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public String handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        logger.error("handleHttpRequestMethodNotSupportedException    不支持當前請求方法", e);
        return "handleHttpRequestMethodNotSupportedException   request_method_not_supported";
    }
 
    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public String handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
        logger.error("handleHttpMediaTypeNotSupportedException不支持當前媒體類型", e);
        return "handleHttpMediaTypeNotSupportedException   content_type_not_supported";
    }
    /**
     * 業務層須要本身聲明異常的狀況
     */
//    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
//    @ExceptionHandler(ServiceException.class)
//    public String handleServiceException(ServiceException e) {
//        logger.error("業務邏輯異常", e);
//        return "業務邏輯異常:" + e.getMessage();
//    }
    /**
     * 操做數據或庫出現異常
     */
//    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
//    @ExceptionHandler(DataDoException.class)
//    public String handleException(DataDoException e) {
//        logger.error("操做數據庫出現異常:", e);
//        return "操做數據庫出現異常:字段重複、有外鍵關聯等";
//    }
 
    /**
     * 500 - Internal Server Error
     */
//   @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
//    @ExceptionHandler(Exception.class)
//    public String handleException(Exception e) {
//        logger.error("通用異常", e);
//        return "500通用異常:" + e.getMessage();
//    }
 
    /**
     * 獲取其它異常。包括500
     * @param e
     * @return
     * @throws Exception
     */
   @ExceptionHandler(value = Exception.class)
    public String defaultErrorHandler(Exception e){
        logger.error("defaultErrorHandler   Exception", e);
 
        return "defaultErrorHandler  其它異常:" + e.getMessage();
 
    }
 
 
 
}
 數據庫

相關文章
相關標籤/搜索