-
1 .创建自己的异常包
public class MyException extends RuntimeException { public MyException(String message){ super(message); } }
-
2 .定义一个异常的实体类
mport java.io.Serializable; public class ErroeMessage implements Serializable { private Integer code; private String message; public ErroeMessage(Integer code, String message) { this.code = code; this.message = message; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
-
3 . 定义一个全局异常类
import com.lbzheng.entities.ErroeMessage; import com.lbzheng.exceptions.MyException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; //捕获所有的自定义异常 @RestControllerAdvice public class CustomExceptionHandler { @ExceptionHandler(value = {MyException.class}) @ResponseStatus(code = HttpStatus.BAD_REQUEST) public ErroeMessage fandlerError(MyException message){ return new ErroeMessage(1000,message.getMessage()); } }
SpringBoot 自定义异常 RestControllerAdvice
最新推荐文章于 2023-11-29 11:48:43 发布