springboot with hibernate Internal Server Error但状态码为200

时间:2017-12-13 00:42:21

标签: java spring hibernate spring-boot swagger

我是Spring的新手,我创建了一个包含divSpring-bootHibernate的小型网络服务。这是我的HomeController:

Swagger

一切都运行良好,除了我不明白为什么当我遇到内部服务器错误时我得到package io.swagger.configuration; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * Home redirection to swagger api documentation */ @Controller public class HomeController { @RequestMapping(value = "/") public String index() { System.out.println("swagger-ui.html"); return "redirect:swagger-ui.html"; } } 这个主体,例如:

status 200

还有发射器:

{
    "timestamp": "2017-12-12T23:52:02.306+0000",
    "status": 500,
    "error": "Internal Server Error",
    "exception": "javax.persistence.PersistenceException",
    "message": "org.hibernate.exception.ConstraintViolationException: could not execute statement",
    "path": "/example/members/1031/subscriptions"
}

配置:

package io.swagger;

import org.apache.commons.logging.LogFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
@ComponentScan(basePackages = "io.swagger")
public class Swagger2SpringBoot extends SpringBootServletInitializer implements CommandLineRunner {

    @Override
    public void run(String... arg0) throws Exception {
        if (arg0.length > 0 && arg0[0].equals("exitcode")) {
            throw new ExitException();
        }
    }

    public static void main(String[] args) throws Exception {

        LogFactory.getLog(Swagger2SpringBoot.class).warn("test");

        new SpringApplication(Swagger2SpringBoot.class).run(args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Swagger2SpringBoot.class);
    }

    class ExitException extends RuntimeException implements ExitCodeGenerator {
        private static final long serialVersionUID = 1L;

        @Override
        public int getExitCode() {
            return 10;
        }

    }
}

Swagger的另一个:

package io.swagger;

import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {

      /**
       * Make sure dates are serialised in
       * ISO-8601 format instead as timestamps
       */
      @Override
      public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
          for (HttpMessageConverter<?> converter : converters) {
              if (converter instanceof MappingJackson2HttpMessageConverter) {
                  MappingJackson2HttpMessageConverter jsonMessageConverter  = (MappingJackson2HttpMessageConverter) converter;
                  ObjectMapper objectMapper  = jsonMessageConverter.getObjectMapper();
                  objectMapper.disable(
                    SerializationFeature.WRITE_DATES_AS_TIMESTAMPS
                  );
                  break;
              }
          }
      }
}

这是我的一个控制器,它们都很相似:

package io.swagger.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
public class SwaggerDocumentationConfig {

    ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("**** API").description("No description").license("").licenseUrl("")
                .termsOfServiceUrl("www.****.com").version("1.0.0")
                .contact(new Contact("", "", "****@****.com")).build();
    }

    @Bean
    public Docket customImplementation() {
        return new Docket(DocumentationType.SWAGGER_2).select()
                .apis(RequestHandlerSelectors.basePackage("io.swagger.api")).build().apiInfo(apiInfo());
    }

}

那么,如果我收到服务器错误,为什么我会有这200个状态呢?至少我想生成package io.swagger.api; import java.util.List; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.model.Comment; @Api public interface CommentsApi { @ApiOperation(value = "Create a comment of an outing", notes = "", response = Comment.class) @ApiResponses(value = { @ApiResponse(code = 201, message = "Status 201", response = Comment.class) }) @RequestMapping(value = "/outings/{outingId}/comments", produces = { "application/json" }, method = RequestMethod.POST) ResponseEntity<Comment> outingsCommentsPost( @ApiParam(value = "", required = true) @PathVariable("outingId") String outingId , @ApiParam(value = "", required = true) @RequestBody Comment body ); @ApiOperation(value = "Update a comment of on outing", notes = "", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 202, message = "Status 202", response = Void.class) }) @RequestMapping(value = "/outings/{outingId}/comments/{commentId}", produces = { "application/json" }, method = RequestMethod.PUT) ResponseEntity<Void> outingsCommentsPut( @ApiParam(value = "", required = true) @PathVariable("outingId") String outingId , @ApiParam(value = "", required = true) @PathVariable("commentId") String commentId , @ApiParam(value = "", required = true) @RequestBody Comment body ); @ApiOperation(value = "Delete a comment", notes = "", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Status 200", response = Void.class) }) @RequestMapping(value = "/outings/{outingId}/comments/{commentId}", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.DELETE) ResponseEntity<Void> outingsCommentsDelete( @ApiParam(value = "", required = true) @PathVariable("outingId") String outingId , @ApiParam(value = "", required = true) @PathVariable("commentId") String commentId ); @ApiOperation(value = "Comments list of an outing", notes = "", response = Comment.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "Status 200", response = Comment.class) }) @RequestMapping(value = "/outings/{outingId}/comments", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.GET) ResponseEntity<List<Comment>> outingsCommentsGet( @ApiParam(value = "", required = true) @PathVariable("outingId") String outingId , @ApiParam(value = "") @RequestParam(value = "page", required = false) Integer page ); @ApiOperation(value = "Comments list of a member", notes = "", response = Comment.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "Status 200", response = Comment.class) }) @RequestMapping(value = "/members/{memberId}/comments", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.GET) ResponseEntity<List<Comment>> membersCommentsGet( @ApiParam(value = "", required = true) @PathVariable("memberId") String outingId , @ApiParam(value = "") @RequestParam(value = "page", required = false) Integer page ); } ,200表示一切都很好,显然不是。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

看来我已经实现了一个自定义错误控制器,从我的swagger文件生成代码,我删除了它,现在一切正常。