开发中经常遇到一个问题,当程序中抛出未处理的异常时,总是会返回一段HTML的错误信息,在restful接口中这不是我们想要的,我们会希望当用户请求接口后,错误信息以json的格式返回。
本文主要讲解spring通过注解@ExceptionHandler解决上述问题。首先简要介绍一下@ExceptionHandler的作用:当一个Controller中含有@ExceptionHandler注解的方法时,当其它Controller抛出未处理的异常时,此方法将统一接收处理。
废话少说,直接上代码:
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("错误信息统一处理。");
}
}
演示截图: