自定义异常处理

spring 中的异常处理机制可以处理大部分异常,如果想要获取 message 以外的异常信息,需要其他处理,自定义异常来处理

自定义异常步骤:

1、定义异常类,实现Exception() 或 RuntimeException()

package com.llangzh.exception;

public class UserNotExistException extends RuntimeException{
	private static final long serialVersionUID = 1L;

	private String id;

	public UserNotExistException(String id) {
		super("用户出现自定义异常");
		this.id = id;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
}

2、自定义异常处理的 Handler

package com.llangzh.handler;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
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.bind.annotation.ResponseStatus;

import com.llangzh.exception.UserNotExistException;

@ControllerAdvice
public class MyExceptionHandler {

	@ExceptionHandler(UserNotExistException.class)
	@ResponseBody
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public Map<String, Object> userNotExistExceptionHandler(UserNotExistException ex){
		Map<String, Object> handlerMap = new HashMap<String, Object>();
		handlerMap.put("id", ex.getId());
		handlerMap.put("message", ex.getMessage());
		return handlerMap;
	}
}

注解作用:

@ControllerAdvice:标明此类用于处理 Controller 抛出的异常

@ExceptionHandler:指定方法要处理的异常

@ResponseBody:返回json

@ResponseStatus:指定返回的 http 的状态码

3、使用自定义异常处理

package com.llangzh.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.llangzh.exception.UserNotExistException;

@RestController()
public class UserController {
	
	@GetMapping("/{id:\\d+}")
	public String testException(@PathVariable String id) throws Exception {
		throw new UserNotExistException(id);
	}
}

测试:

url:http://localhost:8080/1

返回结果:{"id":"1","message":"用户出现自定义异常"}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值