spring boot @ControllerAdvice 增强注解使用

一、接口接受Date参数,可以传入String类型

@ControllerAdvice
public class CommonDateAdvice {
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), false));
    }
}

二、统一异常返回

2.1、异常返回主要实现

@ControllerAdvice
@ResponseBody
public class CommonExceptionAdvice extends BaseExceptionAdvice {

    private Logger logger = LogManager.getLogger(this.getClass());


     /**
     * 401 - Bad Request
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(TokenValidationException.class)
    public Object missingTokenException(TokenValidationException e,
            WebRequest request) {
        logger.error(e);
        return renderError(HttpStatus.BAD_REQUEST, request, "required_parameter_is_not_present");
    }


    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Object handleMissingServletRequestParameterException(MissingServletRequestParameterException e,
        WebRequest request) {
        logger.error(e);
        return renderError(HttpStatus.BAD_REQUEST, request, "required_parameter_is_not_present");
    }

    /**
     * 400 - Bad Request
     */    
      @ResponseStatus(HttpStatus.BAD_REQUEST)
      @ExceptionHandler(HttpMessageNotReadableException.class)
      public Object handleHttpMessageNotReadableException(HttpMessageNotReadableException e, WebRequest request) {
        logger.error(e);

        return renderError(HttpStatus.BAD_REQUEST, request, "could_not_read_json");
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e, WebRequest request) {
        logger.error(e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        return renderError(HttpStatus.BAD_REQUEST, request, message);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public Object handleBindException(BindException e, WebRequest request) {
        logger.error(e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        return renderError(HttpStatus.BAD_REQUEST, request, message);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ConstraintViolationException.class)
    public Object handleServiceException(ConstraintViolationException e, WebRequest request) {
        logger.error(e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        ConstraintViolation<?> violation = violations.iterator().next();
        String message = violation.getMessage();
        return renderError(HttpStatus.BAD_REQUEST, request, message);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public Object handleValidationException(ValidationException e, WebRequest request) {
        logger.error(e);
        return renderError(HttpStatus.BAD_REQUEST, request, "validation_exception");
    }
    /**
     * 404 - Bad Request
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(HttpException.class)
    public Object notFoundPage(Exception e, WebRequest request) {
        logger.error(e);
        return renderError(HttpStatus.BAD_REQUEST, request, "not found page");
    }

    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Object handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e,
        WebRequest request) {
        logger.error(e);
        logger.error(request.getContextPath());
        return renderError(HttpStatus.METHOD_NOT_ALLOWED, request, "request_method_not_supported");
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public Object handleHttpMediaTypeNotSupportedException(Exception e, WebRequest request) {
        logger.error(e);
        return renderError(HttpStatus.UNSUPPORTED_MEDIA_TYPE, request, "content_type_not_supported");
    }

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(MyException.class)
    public Object handleServiceException(MyException e, WebRequest request) {
        logger.error(e);
        return renderError(HttpStatus.INTERNAL_SERVER_ERROR, request, e.getMessage());
    }

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(Exception.class)
    public Object handleException(Exception e, WebRequest request) {
        logger.error(e);
        return renderError(HttpStatus.NOT_FOUND, request, e.getMessage());
    }

    /**
     * 操作数据库出现异常:名称重复,外键关联
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(DataIntegrityViolationException.class)
    public Object handleException(DataIntegrityViolationException e, WebRequest request) {
        logger.error(e);
        return renderError(HttpStatus.INTERNAL_SERVER_ERROR, request, "操作数据库出现异常:字段重复、有外键关联等");
    }



}

2.2、基础类实现

public class BaseExceptionAdvice {
    /**
     * 失败
     * 
     * @return {Object}
     */
    public Object renderError(HttpStatus status, WebRequest request) {
        Result result = new Result();
        result.setSuccess(false);
        result.setStatusValue(status.value());
        result.setPath(request.getContextPath());
        return result;
    }

    /**
     * 失败
     * 
     * @return {Object}
     */
    public Object renderError(Integer status, String msg, String path) {
        Result result = new Result();
        result.setSuccess(false);
        result.setStatusValue(status);
        result.setMsg(msg);
        result.setPath(path);
        return result;
    }

    /**
     * 失败
     * 
     * @return {Object}
     */
    public Object renderError(HttpStatus status, WebRequest request, String msg) {
        Result result = new Result();
        result.setSuccess(false);
        result.setStatusValue(status.value());
        ServletWebRequest req = (ServletWebRequest) request;
        result.setPath(req.getRequest().getServletPath());
        result.setMsg(msg);
        return result;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,651评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,468评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,931评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,218评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,234评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,198评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,084评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,926评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,341评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,563评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,731评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,430评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,036评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,676评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,829评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,743评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,629评论 2 354

推荐阅读更多精彩内容

  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 10,961评论 6 13
  • 这是16年5月份编辑的一份比较杂乱适合自己观看的学习记录文档,今天18年5月份再次想写文章,发现简书还为我保存起的...
    Jenaral阅读 2,752评论 2 9
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,788评论 0 38
  • 朗诵的十大好处 大声朗诵、活动思维、加强写作、提高气质、增强自信、有益身心健康! 一、有利于开发右脑。因为大声读实...
    春暖花开6091阅读 1,522评论 0 0
  • 最近在看《知否知否应是绿肥红瘦》,正看到盛墨兰私会梁六,盛父撞破二人私会。 紧接着,林噙霜散布流言,要挟盛家等望族...
    乔疯star阅读 149评论 0 0