Spring Controller異常處理@ExceptionHandler,返回json數(shù)據(jù)

開發(fā)中經(jīng)常遇到一個問題,當程序中拋出未處理的異常時,總是會返回一段HTML的錯誤信息,在restful接口中這不是我們想要的,我們會希望當用戶請求接口后,錯誤信息以json的格式返回。

本文主要講解spring通過注解@ExceptionHandler解決上述問題。首先簡要介紹一下@ExceptionHandler的作用:當一個Controller中含有@ExceptionHandler注解的方法時,當其它Controller拋出未處理的異常時,此方法將統(tǒng)一接收處理。

廢話少說,直接上代碼:

import com.google.gson.Gson;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.Serializable;
/**
 * Created by yuanjian on 6/27/17.
 */
public class ExceptionHandlerController {
    @ExceptionHandler
    @ResponseBody
    public Object expHandler(Exception e) {
        return new Result(e.getMessage(), 500);
    }
}
class Result<D> implements Serializable {
    private int status;
    private D data;
    private String message;
    public Result() {
    }
    public Result(String message, Integer code) {
        this.status = code;
        this.message = message;
    }
    @Override
    public String toString() {
        return new Gson().toJson(this);
    }
}
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @auther yuanjian
 * @create 7/5/17
 * @email liuyj@shinemo.com
 */
@Controller
@RequestMapping("/exception/*")
public class TestExceptionController extends ExceptionHandlerController {

    @RequestMapping(value = "/test",method = RequestMethod.POST,consumes = "application/json;charset=UTF-8",produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String exceptionTest(){
        throw new RuntimeException("錯誤信息統(tǒng)一處理。");
    }

}

演示截圖:

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容