首先我的项目是一个为移动端提供的json数据的,当后台报错时如果为移动端返回一个错误页面显得非常不友好,于是通过ControllerAdvice注解返回json数据。

首先创建一个异常处理类:

package com.gefufeng.controller;

import com.gefufeng.common.exception.KnownBizException;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
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 javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map; /**
* Created by gefufeng on 16/7/18.
*/
@ControllerAdvice
public class ApplicationControllerExceptionHandler {
private static final Logger LOGGER = LogManager.getLogger(ApplicationControllerExceptionHandler.class); @ExceptionHandler(value = Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public Map<String, Object> handlerError(HttpServletRequest req, Exception e) {
map.put("tip", "此错误说明调用接口失败,失败原因见msg,如果msg为空,联系后台");
map.put("msg", msg);
map.put("path", req.getRequestURI());
map.put("params", req.getParameterMap());
map.put("status", "0");
return map;
}
}

加上ControllerAdvice注解,注意这个类是在controller包下面,因为spring需要扫描到,

代码中的:

@ExceptionHandler(value = Exception.class)

表示捕捉到所有的异常,你也可以捕捉一个你自定义的异常,比如:

    @ExceptionHandler(BusinessException.class)
@ResponseBody//这里加上这个注解才能返回json数据
public void handleBizExp(HttpServletRequest request, Exception ex){ } @ExceptionHandler(SQLException.class)
public ModelAndView handSql(Exception ex){
ModelAndView mv = new ModelAndView();
return mv;
}

然后我在一个接口中故意抛出一个异常:

@RestController
@RequestMapping(value = "/customer",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class CustomerController extends BaseController{
@Autowired
CustomerService customerService; @RequestMapping(value = "/getcustomer",method = RequestMethod.GET)
public String getCustomer(){
logger.info(EnvironmentUtils.isTest());
List<Customer> customers = customerService.getCustomerList();
throw new KnownBizException("已知的异常");
}
}

最后后台返回的数据是:

{
"msg": "已知的异常",
"path": "/myschool/customer/getcustomer",
"tip": "此错误说明调用接口失败,失败原因见msg,如果msg为空,联系后台",
"params": {},
"status": "0"
}
 

spring mvc异常统一处理(ControllerAdvice注解)的更多相关文章

  1. 【Java Web开发学习】Spring MVC异常统一处理

    [Java Web开发学习]Spring MVC异常统一处理 文采有限,若有错误,欢迎留言指正. 转载:https://www.cnblogs.com/yangchongxing/p/9271900. ...

  2. spring mvc 异常统一处理方式

    springMVC提供的异常处理主要有两种方式: 一种是直接实现自己的HandlerExceptionResolver: 另一种是使用注解的方式实现一个专门用于处理异常的Controller——Exc ...

  3. Spring MVC异常统一处理的三种方式

    Spring 统一异常处理有 3 种方式,分别为: 使用 @ ExceptionHandler 注解 实现 HandlerExceptionResolver 接口 使用 @controlleradvi ...

  4. Spring MVC异常统一处理(包括普通请求异常以及ajax请求异常)

    通常SpringMVC对异常的配置都是返回某个jsp视图给用户,但是通过ajax方式发起请求,即使发生异常,前台也无法获得任何异常提示信息.因此需要对异常进行统一的处理,对于普通请求以及ajax请求的 ...

  5. Spring MVC异常统一处理

    package com.shzq.common.exception; import java.io.PrintWriter;import java.io.StringWriter;import jav ...

  6. spring mvc 异常统一处理

    摘自: http://gaojiewyh.iteye.com/blog/1297746  

  7. Spring MVC 4常用的那些注解

    Spring从2.5版本开始在编程中引入注解,用户可以使用@RequestMapping, @RequestParam, @ModelAttribute等等这样类似的注解.到目前为止,Spring的版 ...

  8. [转]Spring MVC 4常用的那些注解

    Spring从2.5版本开始在编程中引入注解,用户可以使用@RequestMapping, @RequestParam, @ModelAttribute等等这样类似的注解.到目前为止,Spring的版 ...

  9. 详解Spring MVC 4常用的那些注解

    Spring从2.5版本开始在编程中引入注解,用户可以使用@RequestMapping, @RequestParam, @ModelAttribute等等这样类似的注解.到目前为止,Spring的版 ...

随机推荐

  1. C段渗透攻击必看的技术知识

    假设想攻击的主机IP是:61.139.1.79 同一子网下我们已有权限的主机IP是:61.139.1.88并可以3389登陆   第一步: tracert 61.139.1.1   C:\WIN200 ...

  2. Sublime Text3中Autoprefixer失效解决方法

    进入CSS文件,默认配置在按下快捷键(Ctrl+Shift+P)后输入Autoprefix,你会发觉它什么事也没干,然后--这什么鬼?抓狂ing-- 原来是因为这玩意还要配置下,以下为配置方法: Pr ...

  3. NSCache

    今天在优化的时候,用了NSCache,感觉没什么两样(视觉上).按理内存缓存,怎么也比从硬盘读取的要快.. dispatch_async(dispatch_get_global_queue(, ), ...

  4. Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException:

    严重: Exception sending context initialized event to listener instance of class org.springframework.we ...

  5. 解决ThinkPHP Call to a member function assign() on a non-object

    <ignore_js_op> assign是tp模板输出变量的一个方法.没有object只能说没实例化...<ignore_js_op> 经过几番思索,终于发现了.原来是Act ...

  6. Cannot find `aapt.exe`. Please install the Android SDK Build-tools package

    Google has updated their SDK tools ("Android SDK Tools" Rev. 23) in a way that also requir ...

  7. ServletConfig 可以做啥

    1.获得 servlet配置的servletname 2.获得servlet 配置的  getInitParameter("keyname") 3.获得servlet配置的 所有的 ...

  8. Linux下安装OpenCV+Python支持

    以下说明在Linux下Python和OpenCV结合安装的过程,Python要使用OpenCV模块,则必须导入OpenCV提供的包,所以要提供Python支持,首先在安装OpenCV前安装必要的组件, ...

  9. BubbleSort冒泡排序

    #include <stdio.h>void BubbleSort(int *a,int n);int main(void){ int arr[10] = {2,4,6,8,0,1,3,5 ...

  10. tensorflow的安装

    binary安装(推荐) 注意需要能访问外网 Install pip (or pip3 for python3) if it is not already installed: # Ubuntu/Li ...