Spring MVC 异常处理

一、自定义异常

这里不做Spring MVC基本说明和简单配置,直接进入异常处理环节。

自定义异常类用于系统内部已经识别的异常,提前做好了应对这类异常的准备,类文件如下:

package com.dasheng.util;

public class MySystemException extends Exception {
    private static final long serialVersionUID = 7775604244452461918L;
    private String message;    
    public MySystemException() {
    }
    public MySystemException(String message) {
        super(message);
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

如果有多个自定义的异常类,可以通过继承,灵活进行控制。

二、实现异常处理类

通过Spring MVC的注解@ControllerAdvice 实现自动加载bean,IOC的精华。。

注解@ExceptionHandler用来指定所需处理的异常类型;@ResponseBody用来指定数据放回的方式。实现如下:

package com.dasheng.util;

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;

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public @ResponseBody String handleException(HttpServletRequest request, Exception ex) {
        String message = null;
        if (ex instanceof MySystemException) {
            message = ((MySystemException) ex).getMessage();
        } else {
            message = "{'message':'system error, connect developer'}";
        }
        HLogger.error(ex);
        return message;
    }
}

三、产生异常并测试

    Spring MVC REST 服务方式,进行测试,获取JSON对象中不存在的key时抛出JSONException,被上面定义的GlobalExceptionHandler

捕获,并处理。代码如下

package com.dasheng.controller;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.dasheng.util.HLogger;

/**
 * @author dashegn
 * 欢迎 控制器
 */
@RestController
public class WelcomeController {
    
    /**
     * 输出欢迎信息,hello world!
     * 2015年9月26日 下午2:58:58
     * dasheng
     * @return
     */
    @RequestMapping(value = "helloWorld", produces = {"text/html;charset=utf-8"} )
    public String sayHelloWorld() {
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder
                .getRequestAttributes()).getRequest();
        String requestURL = request.getRequestURI();
        HLogger.info(requestURL);
        String hi = "hello world! My name is Dasheng...";        
        return hi;
    }
    
    @RequestMapping(value = "exception", produces = {"text/html;charset=utf-8"} )
    public String handleException() {
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder
                .getRequestAttributes()).getRequest();
        String requestURL = request.getRequestURI();
        HLogger.info(requestURL);
        String hi = "{\"id\":1,\"name\":\"dasheng\"}";
        JSONObject hiJson = JSONObject.fromObject(hi);
        String id = hiJson.getString("id");
        String exception = hiJson.getString("age");  //此处抛出异常
        return hi;
    }
}

  Spring功能强大,逐步探索吧。

转载于:https://www.cnblogs.com/willsuna/p/4926508.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值