首先我的項目是一個為移動端提供的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" }
