package com.lenovo.springboot.exception;
import com.lenovo.springboot.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public Result<?> exceptionHandler(){
return Result.error();
}
@ExceptionHandler(value = CustomException.class)
@ResponseBody
public Result<?> CustomExceptionHandler(CustomException e){
return Result.error(e.getCode(),e.getMessage());
}
}
package com.lenovo.springboot.exception;
import com.lenovo.springboot.common.Result;
import lombok.Data;
import lombok.Getter;
import org.springframework.web.bind.annotation.ControllerAdvice;
@ControllerAdvice
@Data
public class CustomException extends RuntimeException{
private Integer code;
public CustomException(Integer code, String msg) {
super(msg);
this.code=code;
}
public CustomException(String msg) {
super(msg);
this.code=500;
}
}