The exception mapping exception mechanism is an early emergency solution to possible problems in Java programs. In SpringMVC, the exception type can be mapped to a view name in the way of exception mapping, so that users can not see the exception information, but a more friendly interface.
Limitations: This is fine for synchronous requests that require a new page, but for asynchronous requests that require data fragments, the response received by Ajax requests cannot be parsed. Solution:
In the spring – the MVC. XML
<! Configure the exception mapping mechanism --> <! In order to be compatible with the exception message response format of asynchronous requests, So using custom CrowdfundingExceptionResolver class - > < bean id = "simpleMappingExceptionResolver" class="com.crowdfunding.component.resolver.CrowdfundingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="java.lang.Exception">error</prop> </props> </property> </bean>Copy the code
There is no spring-mVC.xml in a distributed architecture so what should we do? Annotations can be used, for example:
@ControllerAdvice public class MyExceptionResolver{ @ExceptionHandler(value=Exception.class) public String resolveException(Exception e, Model model){ model.addAttribute("exception",e); return "error"; }}Copy the code
Override the doResolveException() method of the exception parser
Why rewrite it?
Rewrite the sample
public class CrowdfundingExceptionResolver extends SimpleMappingExceptionResolver { @Override protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {// Determine whether the current request is asynchronous. If x-requested-with is null, it is a synchronous request. X-requested-with: XMLHttpRequest: Ajax request. if ((request.getHeader("accept").contains("application/json") || (request.getHeader("X-Requested-With") ! = null && request.getheader (" x-requested-with "). Contains ("XMLHttpRequest")))) {try {// Create a ResultVO object to encapsulate the Ajax response result ResultVO<String> resultVO = new ResultVO<>(); resultVO.setResult(ResultVO.FAILED); resultVO.setData(ResultVO.NO_DATA); resultVO.setMessage(ex.getMessage()); // Convert a resultVO object to JSON data Gson Gson = new Gson(); String json = gson.toJson(resultVO); // Set response.setContentType(" Application /json; charset=UTF-8"); // Return the resultVO JSON data to the browser response.getwriter ().write(JSON); } catch (IOException e) { e.printStackTrace(); } return null; } return super.doresolveException (request, Response, handler, ex); return super.doresolveException (request, response, handler, ex); }}Copy the code
Gson’s dependency on POM.xml
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
Copy the code