開發(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