在SpringBoot中引发异常

3qpi33ja  于 2022-10-30  发布在  Spring
关注(0)|答案(2)|浏览(143)

因此,我尝试为GET请求抛出一个异常(更多的请求即将到来,但现在我正在处理GET)。在我创建错误包和其中的类之前,我得到了通常的java空指针错误。但是,在我创建它们之后,我只得到了这个
{}
下面是我的类,从异常包开始到控制器
未找到记录异常类

package com.yash.questionnaire.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class RecordNotFoundException extends RuntimeException
{
    public RecordNotFoundException(String exception) {
        super(exception);
    }
}

错误响应类

package com.yash.questionnaire.exception;

import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "error")
public class ErrorResponse
{
    public ErrorResponse(String message, List<String> details) {
        super();
        this.message = message;
        this.details = details;
    }

    //General error message about nature of error
    private String message;

    //Specific errors in API request processing
    private List<String> details;

    //Getter and setters
}

自定义异常处理程序类

package com.yash.questionnaire.exception;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@SuppressWarnings({"unchecked","rawtypes"})
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler
{
    @ExceptionHandler(Exception.class)
    public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
        List<String> details = new ArrayList<>();
        details.add(ex.getLocalizedMessage());
        ErrorResponse error = new ErrorResponse("Server Error", details);
        return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(RecordNotFoundException.class)
    public final ResponseEntity<Object> handleUserNotFoundException(RecordNotFoundException ex, WebRequest request) {
        List<String> details = new ArrayList<>();
        details.add(ex.getLocalizedMessage());
        ErrorResponse error = new ErrorResponse("Record Not Found", details);
        return new ResponseEntity(error, HttpStatus.NOT_FOUND);
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        List<String> details = new ArrayList<>();
        for(ObjectError error : ex.getBindingResult().getAllErrors()) {
            details.add(error.getDefaultMessage());
        }
        ErrorResponse error = new ErrorResponse("Validation Failed", details);
        return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
    }
}

研究控制器类

package com.yash.questionnaire.web;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.yash.questionnaire.exception.RecordNotFoundException;
import com.yash.questionnaire.model.Study;
import com.yash.questionnaire.repository.MapValidationError;
import com.yash.questionnaire.repository.StudyRepository;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
@Api(value= "DDR", description="This API provides the facility to create a new Study")
public class StudyController {

    @Autowired
    private StudyRepository repository;

    @Autowired
    private MapValidationError mapValidationError;    //ToDo: to fetch Json post request

    @ApiOperation(value = "Read a study by study-name")
    @GetMapping("/studies/{studyType}")
    public ResponseEntity<Map<String, Object>> getByStudyType(@ApiParam(value = "Questionnaire StudyType will retrieve", required = true) @PathVariable("studyType") String studyType) {
        try {
            return new ResponseEntity<>(repository.getByStudyType(studyType), HttpStatus.OK);

        } catch (RecordNotFoundException ex) {
            throw new RecordNotFoundException("Invalid studyType : " + studyType);
        }
    }

}

有人能帮我弄清楚如何显示我放在StudyController类中的自定义错误,而不仅仅是{}

ojsjcaue

ojsjcaue1#

也许您应该删除异常类上的@ResponseStatus(HttpStatus.NOT_FOUND)。

bgibtngc

bgibtngc2#

package com.vk.common;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class RecordNotFoundException extends Exception {
    private static final long serialVersionUID = 1L;

    public RecordNotFoundException(String message) {
        super(message);
    }

}

相关问题