springBoot入門總結(九)全局異常捕獲

spring3.2中新增了 @ControllerAdvice (等同於 @RestControllerAdvice + @ResponseBody 註解)
@ControllerAdvice 是 controller 的一個輔助類,最常用的就是作爲全局異常處理的切面類。
@ControllerAdvice 可以指定掃描範圍。
@ControllerAdvice 約定了幾種可行的返回類型。返回 String,表示跳到某個 view;返回 modelAndView;如果是直接返回 model 類的話,需要使用 @ResponseBody 進行 json 轉換。
組合 @ExceptionHandler、@ModelAttribute 應用於被 @RequestMapping 註解的方法之上。

一、@RestControllerAdvice + @ExceptionHandler 捕獲異常

package com.demo.handler;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

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

@RestControllerAdvice
public class GlobalDefaultExceptionHandler {

    /**
     * 捕獲全局異常
     * */
    @ExceptionHandler(value = Exception.class)
    public Map<String,Object> defaultExceptionHandler(){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("status",500);
        map.put("message","系統異常");
        return map;
    }
}
package com.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/error")
public class ErrorController {

    //http://localhost:8080/error/test
    @RequestMapping("/test")
    public String test(){
        int i = 1/0;//拋出異常
        return "success";
    }
}

訪問:http://localhost:8080/error/test

結果:

二、@ControllerAdvice + @ModelAttribute 把值綁定到Model中,使全局@RequestMapping可以獲取到該值

package com.demo.handler;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalDefaultExceptionHandler {

    /**
     * 把值綁定到Model中,使全局@RequestMapping可以獲取到該值
     * */
    @ModelAttribute
    public void addAttributes(Model model){
        model.addAttribute("code","1010");
    }
}

 

package com.demo.controller;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestController {

    /**
     * http://localhost:8080/test/addAttribute
     *
     * 通過 @ModelAttribute 獲取 @ControllerAdvice + @ModelAttribute 設置的值
     * */
    @RequestMapping("/addAttribute")
    public String addAttribute(@ModelAttribute("code") String code){
        return code;
    }
}

訪問:http://localhost:8080/test/addAttribute

結果:

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章