java全局异常处理

自定义异常类


import lombok.Data;

@Data
public class BusinessException extends RuntimeException{

    private Integer code;

    public BusinessException(String message) {
        super(message);
        this.code = 500;
    }

    public BusinessException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public BusinessException(Integer code, String message, Throwable cause) {
        super(message, cause);
        this.code = code;
    }
}

统一异常处理


import com.example.mybatisplusdemo.util.ResultUtil;
import com.example.mybatisplusdemo.vo.Result;
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 GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(BusinessException.class)
    public Result handler(BusinessException e){
        return ResultUtil.fail(e.getCode(),e.getMessage());
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result handler(Exception e){
        return ResultUtil.fail(500,e.getMessage());
    }

}

你可能感兴趣的:(java,开发语言)