网上看到的不错的全局异常处理教程:http://blog.csdn.net/JE_GE/article/details/53326516
项目中使用的注解在访问Controller方法之前拦截,对参数进行校验。
对方法级别的参数进行验证,需要加上如下配置:
package com.redsoft.spirit.config;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
@Configuration
@EnableAutoConfiguration//自动载入应用程序所需的所有Bean——这依赖于Spring Boot在类路径中的查找。
public class FactoryConfig {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor(){
return new MethodValidationPostProcessor();
}
}
- 在Controller类前添加如下如下注解即可拦截。
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.validation.annotation.Validated;
import com.redsoft.epip.service.InfoClickService;
import com.redsoft.epip.service.PersonsInfoService;
import com.redsoft.epip.service.UserService;
import com.redsoft.spirit.entity.JsonResult;
@RestController
@Validated//拦截hibernate的验证注解
public class InfoClickController {
@Autowired
private InfoClickService infoClickService;
@Autowired
private UserService userService;
@Autowired
private PersonsInfoService personsInfoService;
/**
*
* 根据条件取消点赞
* <pre>
* 根据条件取消点赞
* </pre>
*
* @author 李晓东
* @param infoId
* @param userId
* @return
*/
@DeleteMapping(value = "/**/personsInfo/click")
public String deleteInfoClick(@NotBlank(message = "infoId不能为空")String infoId, @NotBlank(message = "userId不能为空")String userId) {
try {
if (personsInfoService.getPersonsInfoById(infoId) == null) {
return new JsonResult(null, "园民信息不存在").failure().toString();
}
if (userService.getById(userId) == null) {
return new JsonResult(null, "用户不存在").failure().toString();
}
infoClickService.deleteInfoClick(infoId, userId);
return new JsonResult().success().toString();
} catch (Exception e) {
return new JsonResult(null, e.getMessage()).failure().toString();
}
}
}
- 统一异常处理结果类
package com.redsoft.spirit.entity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* 处理返回给页面的json结果.
*
* <pre>
* 处理返回给页面的json结果,封装好默认的成功的状态
* </pre>
*
* @author 杨雷
* @since 1.0
*
*/
public class JsonResult {
private int status;
private String msg;
private Object data;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {