Skip to content

Instantly share code, notes, and snippets.

@qlong8807
Created December 5, 2018 03:24
Show Gist options
  • Save qlong8807/e17dc73be9b2793d3fac1ff46296525d to your computer and use it in GitHub Desktop.
Save qlong8807/e17dc73be9b2793d3fac1ff46296525d to your computer and use it in GitHub Desktop.
//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