11.全局统一异常处理

示例

exception/ExceptionHandlerAdvice.java

package com.boot.study.exception;

import java.io.Serializable;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import lombok.Getter;
import lombok.Setter;

@ControllerAdvice
public class ExceptionHandlerAdvice {

	@ResponseBody
	@ExceptionHandler(value = { NullPointerException.class })
	public Res exception(NullPointerException exception) {
		Res res = new Res();
		res.setCode("001");
		res.setMsg("有空指針");

		return res;
	}

	@ResponseBody
	@ExceptionHandler(value = { Throwable.class })
	public Res exception(Throwable throwable) {
		Res res = new Res();
		res.setCode("500");
		res.setMsg("未知异常:" + throwable.getMessage());

		return res;
	}

	@Getter
	@Setter
	public static class Res implements Serializable {
		/**
		 * 
		 */
		private static final long serialVersionUID = 3640012704565708944L;
		private String code;
		private String msg;
	}
}

用到了lombok

controller/HelloController.java

package com.boot.study.controller;

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

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

@RestController
@RequestMapping("/hello")
public class HelloController {

	@GetMapping
	public String hello(String name) {
		System.out.println(name.length()); //空指针异常
		System.out.println(1 / 0); // 未知异常
		return "hello world";
	}
}

资料

Spring boot全局异常统一拦截

Last updated