Created
December 5, 2018 03:24
-
-
Save qlong8807/e17dc73be9b2793d3fac1ff46296525d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//1当普通调用时,一般跳转到自定义的错误页面。 | |
//2当ajax调用时,可返回约定的数据对象,方便页面统一处理。 | |
import java.util.HashMap; | |
import java.util.Map; | |
import javax.servlet.http.HttpServletRequest; | |
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.servlet.ModelAndView; | |
import com.example.config.exception.MyBusinessException; | |
import com.example.config.exception.MyJsonException; | |
@ControllerAdvice | |
public class GlobalExceptionHandler { | |
public static final String DEFAULT_ERROR_VIEW = "error"; | |
@ExceptionHandler(value = MyPageException.class) | |
public ModelAndView businessExceptionHandler(HttpServletRequest req, Exception e) throws Exception { | |
ModelAndView mav = new ModelAndView(); | |
mav.addObject("message", e.getMessage()); | |
mav.setViewName(DEFAULT_ERROR_VIEW); | |
return mav; | |
} | |
@ExceptionHandler(value = MyJsonException.class) | |
@ResponseBody | |
public Map<String, String> jsonExceptionHandler(HttpServletRequest req, Exception e) { | |
Map<String, String> re = new HashMap<String, String>(); | |
re.put("error", "1"); | |
re.put("msg", e.getMessage()); | |
return re; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment