001/*
002 * PermissionsEx
003 * Copyright (C) zml and PermissionsEx contributors
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *    http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package ca.stellardrift.permissionsex.exception;
018
019import net.kyori.adventure.text.Component;
020import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer;
021import net.kyori.adventure.translation.GlobalTranslator;
022import net.kyori.adventure.util.ComponentMessageThrowable;
023import org.checkerframework.checker.nullness.qual.Nullable;
024
025import java.util.Locale;
026
027/**
028 * An exception where PermissionsEx is involved.
029 *
030 * @since 2.0.0
031 */
032public class PermissionsException extends Exception implements ComponentMessageThrowable {
033    private static final long serialVersionUID = 138001301588644173L;
034    private static final Component NULL = Component.text("null");
035
036    private final @Nullable Component message;
037
038    public PermissionsException(final @Nullable Component message) {
039        this.message = message;
040    }
041
042    public PermissionsException(final @Nullable Component message, final @Nullable Throwable cause) {
043        super(cause);
044        this.message = message;
045    }
046
047    @Override
048    public String getMessage() {
049        return getLocalizedMessage();
050    }
051
052    @Override
053    public String getLocalizedMessage() {
054        return getLocalizedMessage(Locale.getDefault());
055    }
056
057    @Override
058    public Component componentMessage() {
059        return this.message == null ? NULL : this.message;
060    }
061
062    public String getLocalizedMessage(Locale locale) {
063        return PlainComponentSerializer.plain().serialize(GlobalTranslator.renderer().render(componentMessage(), locale));
064    }
065}