BizException.java
package com.wl.demo.exception;
/**
* @Author WL
* @Date 2025/2/20 10:20
* @Version 1.0
*/
public class BizException extends RuntimeException {
public BizException(String message) {
super(message);
}
public BizException(Exception e) {
super(e);
}
}
BizExceptionHandler.java
package com.wl.demo.exception;
/**
* 全局异常处理器
*
* @Author WL
* @Date 2025/2/20 10:20
* @Version 1.0
*/
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class BizExceptionHandler {
/**
* 此处的Result为接口的返回值
*/
@ExceptionHandler(BizException.class)
public ResponseEntity<Result<Object>> handleBizException(BizException e) {
return ResponseEntity.ok(Result.error(e.getMessage()));
}
}
Test.java
package com.wl.demo.test;
import com.wl.demo.exception.BizException;
/**
* @Author WL
* @Date 2025/2/20 10:32
* @Version 1.0
*/
public class Test {
public static void main(String[] args) {
try {
System.err.println(Integer.parseInt("123"));
} catch (Exception e) {
// 若抛出此异常,返回
throw new BizException("类型转换失败!");
}
}
}