001/*
002 * This file is part of the Keycloak Moodle authenticator
003 * Copyright (C) 2024 Michael N. Lipp
004 *
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Lesser General Public License as published
007 * by the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
013 * License for more details.
014 *
015 * You should have received a copy of the GNU Lesser General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jdrupes.keycloak.moodleauth.moodle;
020
021import java.io.IOException;
022import java.util.Optional;
023import org.jdrupes.keycloak.moodleauth.moodle.model.MoodleErrorValues;
024
025/**
026 * Represents a moodle exception
027 */
028@SuppressWarnings({ "serial" })
029public class MoodleException extends IOException {
030
031    private final MoodleErrorValues moodleError;
032
033    /**
034     * Instantiates a new moodle exception.
035     *
036     * @param error the error
037     */
038    public MoodleException(MoodleErrorValues error) {
039        super(error.getErrorcode());
040        this.moodleError = error;
041    }
042
043    /**
044     * Returns the error reported by moodle.
045     *
046     * @return the string
047     */
048    public String error() {
049        return moodleError.getError();
050    }
051
052    /**
053     * Returns the error code reported by moodle.
054     *
055     * @return the string
056     */
057    public String errorCode() {
058        return moodleError.getErrorcode();
059    }
060
061    /**
062     * Returns the message provided by moodle.
063     *
064     * @return the string
065     */
066    public String message() {
067        return moodleError.getMessage();
068    }
069
070    /**
071     * Return the exception provided by moodle.
072     *
073     * @return the string
074     */
075    public String exception() {
076        return moodleError.getException();
077    }
078
079    @Override
080    public String toString() {
081        return Optional.ofNullable(moodleError.getErrorcode())
082            .map(s -> "Error code: " + s).orElse("")
083            + Optional.ofNullable(moodleError.getError())
084                .map(s -> ", error: " + s).orElse("")
085            + Optional.ofNullable(moodleError.getMessage())
086                .map(s -> ", message: " + s).orElse("")
087            + Optional.ofNullable(moodleError.getException())
088                .map(s -> ", exception: " + s).orElse("");
089
090    }
091}