Spring 全局异常、数据绑定

2019-01-16  本文已影响0人  胖嘟嘟洒酒疯

全局异常处理

异常处理类配置

@ControllerAdvice
public class ControllerAdviceConfig {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String sessionNotFoundExceptionHandler(HttpServletRequest request, Exception e) throws Exception {
        return "Controller Exception handle";
    }
}

Controllere层

    @GetMapping("/exception/{id}")
    public String exception(@PathVariable("id") Integer id) throws Exception {
        if (1 == id) {
            throw new Exception("异常");
        }
        return "exception";
    }

参数数据解析

在配置中添加

    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        webDataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {

            @Override
            public void setAsText(String text) {
                try {
                    setValue(new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").parse(text));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public String getAsText() {
                return new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(getValue());
            }
        });
    }
上一篇 下一篇

猜你喜欢

热点阅读