小强哥博客

小强哥,小强哥博客,技术大咖

quezon项目总结,ControllerAdvice全局异常拦截使用

最近在在做后端接口,接收客户端传输过来的json数据,然后入库。

项目使用的是springboot程序,接收json数据使用的是@RequestBody注解,如下,

@RequestMapping(value = "/message/send", method = RequestMethod.POST)
public <T> ResponseEntity<ObjectNode> postMessageBuSend(@RequestBody MessageVO messageVO) {
	ObjectNode root = JsonUtil.createObjectNode();
	return new ResponseEntity<ObjectNode>(root,HttpStatus.OK);
}

使用@RequestBody注解将json数据映射到MessageVO对象中,这就需要标准的json格式,如果非标准json格式就会报错,如下,

错误的json格式

{
	"bu":"xxxx",
	"content":"""11111222222222222"""
}

报错信息

{
    "timestamp": 1501222470973,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.http.converter.HttpMessageNotReadableException",
    "message": "JSON parse error: Unexpected character ('\"' (code 34)): was expecting comma to separate Object entries; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('\"' (code 34)): was expecting comma to separate Object entries\n at [Source: java.io.PushbackInputStream@3e61b6f4; line: 3, column: 15]",
    "path": "/api/weixin/message/bu/send"
}

这个报错内容实际上不是我想要的,我需要的格式如下,

{
    "message": "客户端数据无法识别"
}

我需要的格式很简单,可以自定义。

这就需要使用spring全局异常处理,创建一个类,在类上加上@ControllerAdvice注解,使用@ExceptionHandler注解标记需要拦截的异常,没有其它配置了,如下代码,

package com.eju.ess.common.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

import com.eju.ess.common.utils.json.JsonUtil;
import com.fasterxml.jackson.databind.node.ObjectNode;

@ControllerAdvice
public class SpringExceptionHandler {
	@ExceptionHandler(value = { HttpMessageNotReadableException.class })
	public ResponseEntity<ObjectNode> httpMessageNotReadableException(Exception e, WebRequest req) {
		ObjectNode root = JsonUtil.createObjectNode();
		root.put("message", "客户端数据无法识别");
		return new ResponseEntity<ObjectNode>(root, HttpStatus.BAD_REQUEST);
	}
	
	@ExceptionHandler(value = { HttpRequestMethodNotSupportedException.class })
	public ResponseEntity<ObjectNode> httpRequestMethodNotSupportedException(Exception e, WebRequest req) {
		ObjectNode root = JsonUtil.createObjectNode();
		root.put("message", "restful请求无法识别");
		return new ResponseEntity<ObjectNode>(root, HttpStatus.METHOD_NOT_ALLOWED);
	}
}