SpringBoot--返回值到页面(异常处理)
同上一篇一样,加入了异常处理。
目录结构:
ErrorInfo:
public class ErrorInfo<T> {
public static final Integer OK = 0;
public static final Integer ERROR = 100;
private Integer code;
private String message;
private String url;
private T data;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public static Integer getOK() {
return OK;
}
public static Integer getERROR() {
return ERROR;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
MyException :
public class MyException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public MyException(String message) {
super(message);
}
}
GlobalExceptionHandler:
import com.didispace.dto.ErrorInfo;
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 javax.servlet.http.HttpServletRequest;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", req.getRequestURL());
mav.setViewName("error");
return mav;
}
@ExceptionHandler(value = MyException.class)
@ResponseBody
public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception {
ErrorInfo<String> r = new ErrorInfo<>();
r.setMessage(e.getMessage());
r.setCode(ErrorInfo.ERROR);
r.setData("Some Data");
r.setUrl(req.getRequestURL().toString());
return r;
}
}
import com.didispace.exception.MyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
/**
*/
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello() throws Exception {
throw new Exception("发生错误");
}
@RequestMapping("/json")
public String json() throws MyException {
throw new MyException("发生错误2");
}
@RequestMapping("/")
public String index(ModelMap map) {
map.addAttribute("host", "http://blog.didispace.com");
return "index";
}
}