@RestControllerAdvice注解使用


 

  在spring 3.2中,新增了@ControllerAdvice,@RestControllerAdvice 注解,可以用於定義@ExceptionHandler、@InitBinder、@ModelAttribute,並應用到所有@RequestMapping中。參考幫助文檔@RestControllerAdvice 是組件注解,他使得其實現類能夠被classpath掃描自動發現,如果應用是通過MVC命令空間或MVC Java編程方式配置,那么該特性默認是自動開啟的

  主要配合@ExceptionHandler使用,統一處理異常情況。下面的ResponseEntity、ResponseData 都是項目自定義的返回對象。

  

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 處理運行異常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
        log.error("", ex);
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
    }

    /**
     * 用來捕獲404,400這種無法到達controller的錯誤
     *
     * @param ex
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseData defaultErrorHandler(Exception ex) throws Exception {
        log.error("", ex);
        ResponseData<Object> result = new ResponseData<Object>();
        result.setMessage(ex.getMessage());
        if (ex instanceof NoHandlerFoundException) {
            result.setCode("404");
        } else {
            result.setCode("500");
        }
        result.setData(null);
        result.setSuccess(false);
        return result;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM