博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring 全局异常处理
阅读量:7023 次
发布时间:2019-06-28

本文共 1255 字,大约阅读时间需要 4 分钟。

hot3.png

使用注解处理异常

  • 异常处理类
package com.uc.advice;import com.uc.enums.Code;import org.apache.log4j.Logger;import org.springframework.web.bind.MissingServletRequestParameterException;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;import java.util.HashMap;import java.util.Map;/** * 全局异常处理 * Created by yanhao on 2017/6/5. */@ControllerAdvicepublic class GlobalExceptionHandler {    private final Logger logger = Logger.getLogger(GlobalExceptionHandler.class);    // Exception处理    @ExceptionHandler(Exception.class)    @ResponseBody    public Object handle(Exception e) {        logger.warn("Exception: " + e.getMessage());        // 返回内容        Map
result = new HashMap
(); result.put("message", e.getMessage()); // 请求参数为空的异常 if(e instanceof MissingServletRequestParameterException) { result.put("code", Code.PARAM_MISSING.getCode()); } // 业务失败返回 return result; }}
  • 产生MissingServletRequestParameterException的地方
// required 是true情况下,为传值@RequestParam(value = "mode", required = true)String mode

转载于:https://my.oschina.net/yan5845hao/blog/914621

你可能感兴趣的文章
CSS布局:水平居中
查看>>
【HTTP】WireShark中获取Content-Encoding: gzip时的响应内容
查看>>
一些组织和个人网站
查看>>
二叉树应用进阶之折纸(二叉树的右根左遍历)
查看>>
运维相关开源项目
查看>>
Lua MD5加密字符串
查看>>
Heap & Priority Queue
查看>>
RDA PQ工具使用 (Adi Analysis)
查看>>
LEETCODE
查看>>
织云Lite发布:详解包管理核心能力
查看>>
hadoop04---shell
查看>>
HDU 4419 Colourful Rectangle(线段树)
查看>>
webservice接口的开发和调用
查看>>
【uTenux实验】内存池管理(固定内存池和可变内存池)
查看>>
Android——Android Studio的一些小技巧(转)
查看>>
Spring学习【Spring概述】
查看>>
【Java数据结构学习笔记之一】线性表的存储结构及其代码实现
查看>>
Facebook内部人才建设潜规则
查看>>
巧用test判断来写shell脚本
查看>>
类装载器
查看>>