Spring Controller异常处理@ExceptionHandler,返回json数据

开发中经常遇到一个问题,当程序中抛出未处理的异常时,总是会返回一段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("错误信息统一处理。");
    }

}

演示截图:

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容