对于Controller的异常处理,分为两种,一种是对已知的异常处理,一种是未知的异常处理

1、定义自定义异常类

/**
* @author hzc
*
*/
public class UserNotExitException extends RuntimeException { /**
*
*/
private static final long serialVersionUID = -6271509017751433865L; private String id; public UserNotExitException(String id) {
super("user not exit");
this.setId(id);
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} }

2、使用@ControllerAdvice

import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.maple.exception.UserNotExitException; @ControllerAdvice
public class ControllerExceptionHandle {
@ExceptionHandler(UserNotExitException.class)
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String, Object> handleUserNotExistException(UserNotExitException ex){
Map<String, Object> result = new HashMap<>();
result.put("id", ex.getId());
result.put("message", ex.getMessage());
return result;
}
}

最新文章

  1. jQuery全选、全不选、反选
  2. 用Metasploit破解Mysql用户名和密码
  3. Google搜索镜像
  4. 常见web服务器错误
  5. NOI2014 全国互测Round2
  6. org.hibernate.HibernateException: could not instantiate RegionFactory [org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge]
  7. 很不错的NGINX URL重写实例
  8. log4net使用具体解释
  9. 201521123045 &lt;java程序设计&gt;第11周学习总结
  10. struts2(六)之ognl表达式与ActionContext、ValueStack
  11. freemarker之数组(十八)
  12. Nginx 配置反向代理后,页面中取绝对URL地址的问题显示代理端口
  13. 手机端-ajax跨域请求滚屏分页
  14. MFC笔记6
  15. Oracle Client安装报错:引用数据不可用于验证此操作系统分发的先决条件
  16. SQL注入(dvwa环境)
  17. Stream Processing 101: From SQL to Streaming SQL in 10 Minutes
  18. Pyhton-Web框架之【Django】
  19. 解决org.apache.rat:apache-rat-plugin:0.8:check (default) on project hbase: Too many unapproved license
  20. 实体框架自定义代码优先约定(EF6以后)

热门文章

  1. sql server 高可用故障转移(6)
  2. jQuery.on() 函数详解 【转载】
  3. github代码搜索技巧
  4. api_request.go
  5. hdu 2899 Strange fuction 模拟退火
  6. ELK 架构之 Elasticsearch、Kibana、Logstash 和 Filebeat 安装配置汇总(6.2.4 版本)
  7. Appium+python的环境搭建!
  8. Netty实现高性能的HTTP服务器
  9. Linux 文件/文件夹无法删除问题解决方案
  10. tday02 上节课复习